2 * imgAreaSelect jQuery plugin
5 * Copyright (c) 2008-2010 Michal Wojciechowski (odyniec.net)
7 * Dual licensed under the MIT (MIT-LICENSE.txt)
8 * and GPL (GPL-LICENSE.txt) licenses.
10 * http://odyniec.net/projects/imgareaselect/
25 $.imgAreaSelect = function (img, options) {
34 $border = div().add(div()).add(div()).add(div()),
35 $outer = div().add(div()).add(div()).add(div()),
52 position = 'absolute',
62 minWidth, minHeight, maxWidth, maxHeight,
70 selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
72 docElem = document.documentElement,
74 $p, d, i, o, w, h, adjusted;
77 return x + imgOfs.left - parOfs.left;
81 return y + imgOfs.top - parOfs.top;
85 return x - imgOfs.left + parOfs.left;
89 return y - imgOfs.top + parOfs.top;
93 return event.pageX - parOfs.left;
97 return event.pageY - parOfs.top;
100 function getSelection(noScale) {
101 var sx = noScale || scaleX, sy = noScale || scaleY;
103 return { x1: round(selection.x1 * sx),
104 y1: round(selection.y1 * sy),
105 x2: round(selection.x2 * sx),
106 y2: round(selection.y2 * sy),
107 width: round(selection.x2 * sx) - round(selection.x1 * sx),
108 height: round(selection.y2 * sy) - round(selection.y1 * sy) };
111 function setSelection(x1, y1, x2, y2, noScale) {
112 var sx = noScale || scaleX, sy = noScale || scaleY;
121 selection.width = selection.x2 - selection.x1;
122 selection.height = selection.y2 - selection.y1;
129 imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
131 imgWidth = $img.width();
132 imgHeight = $img.height();
134 minWidth = options.minWidth || 0;
135 minHeight = options.minHeight || 0;
136 maxWidth = min(options.maxWidth || 1<<24, imgWidth);
137 maxHeight = min(options.maxHeight || 1<<24, imgHeight);
139 if ($().jquery == '1.3.2' && position == 'fixed' &&
140 !docElem['getBoundingClientRect'])
142 imgOfs.top += max(document.body.scrollTop, docElem.scrollTop);
143 imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft);
146 parOfs = $.inArray($parent.css('position'), ['absolute', 'relative']) + 1 ?
147 { left: round($parent.offset().left) - $parent.scrollLeft(),
148 top: round($parent.offset().top) - $parent.scrollTop() } :
149 position == 'fixed' ?
150 { left: $(document).scrollLeft(), top: $(document).scrollTop() } :
156 if (selection.x2 > imgWidth || selection.y2 > imgHeight)
160 function update(resetKeyPress) {
163 $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
164 .add($area).width(w = selection.width).height(h = selection.height);
166 $area.add($border).add($handles).css({ left: 0, top: 0 });
169 .width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
170 .height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
172 $($outer[0]).css({ left: left, top: top,
173 width: selection.x1, height: imgHeight });
174 $($outer[1]).css({ left: left + selection.x1, top: top,
175 width: w, height: selection.y1 });
176 $($outer[2]).css({ left: left + selection.x2, top: top,
177 width: imgWidth - selection.x2, height: imgHeight });
178 $($outer[3]).css({ left: left + selection.x1, top: top + selection.y2,
179 width: w, height: imgHeight - selection.y2 });
181 w -= $handles.outerWidth();
182 h -= $handles.outerHeight();
184 switch ($handles.length) {
186 $($handles[4]).css({ left: w / 2 });
187 $($handles[5]).css({ left: w, top: h / 2 });
188 $($handles[6]).css({ left: w / 2, top: h });
189 $($handles[7]).css({ top: h / 2 });
191 $handles.slice(1,3).css({ left: w });
192 $handles.slice(2,4).css({ top: h });
195 if (resetKeyPress !== false) {
196 if ($.imgAreaSelect.keyPress != docKeyPress)
197 $(document).unbind($.imgAreaSelect.keyPress,
198 $.imgAreaSelect.onKeyPress);
201 $(document)[$.imgAreaSelect.keyPress](
202 $.imgAreaSelect.onKeyPress = docKeyPress);
205 if ($.browser.msie && $border.outerWidth() - $border.innerWidth() == 2) {
206 $border.css('margin', 0);
207 setTimeout(function () { $border.css('margin', 'auto'); }, 0);
211 function doUpdate(resetKeyPress) {
213 update(resetKeyPress);
214 x1 = viewX(selection.x1); y1 = viewY(selection.y1);
215 x2 = viewX(selection.x2); y2 = viewY(selection.y2);
218 function hide($elem, fn) {
219 options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
223 function areaMouseMove(event) {
224 var x = selX(evX(event)) - selection.x1,
225 y = selY(evY(event)) - selection.y1;
231 $box.one('mouseout', function () { adjusted = false; });
236 if (options.resizable) {
237 if (y <= resizeMargin)
239 else if (y >= selection.height - resizeMargin)
241 if (x <= resizeMargin)
243 else if (x >= selection.width - resizeMargin)
247 $box.css('cursor', resize ? resize + '-resize' :
248 options.movable ? 'move' : '');
253 function docMouseUp(event) {
254 $('body').css('cursor', '');
256 if (options.autoHide || selection.width * selection.height == 0)
257 hide($box.add($outer), function () { $(this).hide(); });
259 options.onSelectEnd(img, getSelection());
261 $(document).unbind('mousemove', selectingMouseMove);
262 $box.mousemove(areaMouseMove);
265 function areaMouseDown(event) {
266 if (event.which != 1) return false;
271 $('body').css('cursor', resize + '-resize');
273 x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
274 y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
276 $(document).mousemove(selectingMouseMove)
277 .one('mouseup', docMouseUp);
278 $box.unbind('mousemove', areaMouseMove);
280 else if (options.movable) {
281 startX = left + selection.x1 - evX(event);
282 startY = top + selection.y1 - evY(event);
284 $box.unbind('mousemove', areaMouseMove);
286 $(document).mousemove(movingMouseMove)
287 .one('mouseup', function () {
288 options.onSelectEnd(img, getSelection());
290 $(document).unbind('mousemove', movingMouseMove);
291 $box.mousemove(areaMouseMove);
295 $img.mousedown(event);
300 function fixAspectRatio(xFirst) {
303 x2 = max(left, min(left + imgWidth,
304 x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
306 y2 = round(max(top, min(top + imgHeight,
307 y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
311 y2 = max(top, min(top + imgHeight,
312 y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
313 x2 = round(max(left, min(left + imgWidth,
314 x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
319 function doResize() {
320 x1 = min(x1, left + imgWidth);
321 y1 = min(y1, top + imgHeight);
323 if (abs(x2 - x1) < minWidth) {
324 x2 = x1 - minWidth * (x2 < x1 || -1);
327 x1 = left + minWidth;
328 else if (x2 > left + imgWidth)
329 x1 = left + imgWidth - minWidth;
332 if (abs(y2 - y1) < minHeight) {
333 y2 = y1 - minHeight * (y2 < y1 || -1);
336 y1 = top + minHeight;
337 else if (y2 > top + imgHeight)
338 y1 = top + imgHeight - minHeight;
341 x2 = max(left, min(x2, left + imgWidth));
342 y2 = max(top, min(y2, top + imgHeight));
344 fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio);
346 if (abs(x2 - x1) > maxWidth) {
347 x2 = x1 - maxWidth * (x2 < x1 || -1);
351 if (abs(y2 - y1) > maxHeight) {
352 y2 = y1 - maxHeight * (y2 < y1 || -1);
353 fixAspectRatio(true);
356 selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
357 y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
358 width: abs(x2 - x1), height: abs(y2 - y1) };
362 options.onSelectChange(img, getSelection());
365 function selectingMouseMove(event) {
366 x2 = resize == '' || /w|e/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
367 y2 = resize == '' || /n|s/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
375 function doMove(newX1, newY1) {
376 x2 = (x1 = newX1) + selection.width;
377 y2 = (y1 = newY1) + selection.height;
379 $.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2),
384 options.onSelectChange(img, getSelection());
387 function movingMouseMove(event) {
388 x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
389 y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
393 event.preventDefault();
398 function startSelection() {
408 if ($outer.is(':not(:visible)'))
409 $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
413 $(document).unbind('mouseup', cancelSelection)
414 .mousemove(selectingMouseMove).one('mouseup', docMouseUp);
415 $box.unbind('mousemove', areaMouseMove);
417 options.onSelectStart(img, getSelection());
420 function cancelSelection() {
421 $(document).unbind('mousemove', startSelection);
422 hide($box.add($outer));
424 selection = { x1: selX(x1), y1: selY(y1), x2: selX(x1), y2: selY(y1),
425 width: 0, height: 0 };
427 options.onSelectChange(img, getSelection());
428 options.onSelectEnd(img, getSelection());
431 function imgMouseDown(event) {
432 if (event.which != 1 || $outer.is(':animated')) return false;
435 startX = x1 = evX(event);
436 startY = y1 = evY(event);
438 $(document).one('mousemove', startSelection)
439 .one('mouseup', cancelSelection);
444 function windowResize() {
451 setOptions(options = $.extend({
452 classPrefix: 'imgareaselect',
456 onInit: function () {},
457 onSelectStart: function () {},
458 onSelectChange: function () {},
459 onSelectEnd: function () {}
462 $box.add($outer).css({ visibility: '' });
468 $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
471 setTimeout(function () { options.onInit(img, getSelection()); }, 0);
474 var docKeyPress = function(event) {
475 var k = options.keys, d, t, key = event.keyCode;
477 d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
478 !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
479 !isNaN(k.shift) && event.shiftKey ? k.shift :
480 !isNaN(k.arrows) ? k.arrows : 10;
482 if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
483 (k.ctrl == 'resize' && event.ctrlKey) ||
484 (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
501 fixAspectRatio(true);
515 doMove(max(x1 - d, left), y1);
518 doMove(x1, max(y1 - d, top));
521 doMove(x1 + min(d, imgWidth - selX(x2)), y1);
524 doMove(x1, y1 + min(d, imgHeight - selY(y2)));
534 function styleOptions($elem, props) {
535 for (option in props)
536 if (options[option] !== undefined)
537 $elem.css(props[option], options[option]);
540 function setOptions(newOptions) {
541 if (newOptions.parent)
542 ($parent = $(newOptions.parent)).append($box.add($outer));
544 $.extend(options, newOptions);
548 if (newOptions.handles != null) {
552 i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
555 $handles = $handles.add(div());
557 $handles.addClass(options.classPrefix + '-handle').css({
558 position: 'absolute',
560 zIndex: zIndex + 1 || 1
563 if (!parseInt($handles.css('width')) >= 0)
564 $handles.width(5).height(5);
566 if (o = options.borderWidth)
567 $handles.css({ borderWidth: o, borderStyle: 'solid' });
569 styleOptions($handles, { borderColor1: 'border-color',
570 borderColor2: 'background-color',
571 borderOpacity: 'opacity' });
574 scaleX = options.imageWidth / imgWidth || 1;
575 scaleY = options.imageHeight / imgHeight || 1;
577 if (newOptions.x1 != null) {
578 setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
580 newOptions.show = !newOptions.hide;
584 options.keys = $.extend({ shift: 1, ctrl: 'resize' },
587 $outer.addClass(options.classPrefix + '-outer');
588 $area.addClass(options.classPrefix + '-selection');
589 for (i = 0; i++ < 4;)
590 $($border[i-1]).addClass(options.classPrefix + '-border' + i);
592 styleOptions($area, { selectionColor: 'background-color',
593 selectionOpacity: 'opacity' });
594 styleOptions($border, { borderOpacity: 'opacity',
595 borderWidth: 'border-width' });
596 styleOptions($outer, { outerColor: 'background-color',
597 outerOpacity: 'opacity' });
598 if (o = options.borderColor1)
599 $($border[0]).css({ borderStyle: 'solid', borderColor: o });
600 if (o = options.borderColor2)
601 $($border[1]).css({ borderStyle: 'dashed', borderColor: o });
603 $box.append($area.add($border).add($handles).add($areaOpera));
605 if ($.browser.msie) {
606 if (o = $outer.css('filter').match(/opacity=([0-9]+)/))
607 $outer.css('opacity', o[1]/100);
608 if (o = $border.css('filter').match(/opacity=([0-9]+)/))
609 $border.css('opacity', o[1]/100);
613 hide($box.add($outer));
614 else if (newOptions.show && imgLoaded) {
616 $box.add($outer).fadeIn(options.fadeSpeed||0);
620 aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
622 $img.add($outer).unbind('mousedown', imgMouseDown);
624 if (options.disable || options.enable === false) {
625 $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown);
626 $(window).unbind('resize', windowResize);
629 if (options.enable || options.disable === false) {
630 if (options.resizable || options.movable)
631 $box.mousemove(areaMouseMove).mousedown(areaMouseDown);
633 $(window).resize(windowResize);
636 if (!options.persistent)
637 $img.add($outer).mousedown(imgMouseDown);
640 options.enable = options.disable = undefined;
643 this.remove = function () {
644 $img.unbind('mousedown', imgMouseDown);
645 $box.add($outer).remove();
648 this.getOptions = function () { return options; };
650 this.setOptions = setOptions;
652 this.getSelection = getSelection;
654 this.setSelection = setSelection;
656 this.update = doUpdate;
662 !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
663 if ($p.css('position') == 'fixed')
666 $p = $p.parent(':not(body)');
669 zIndex = options.zIndex || zIndex;
672 $img.attr('unselectable', 'on');
674 $.imgAreaSelect.keyPress = $.browser.msie ||
675 $.browser.safari ? 'keydown' : 'keypress';
678 $areaOpera = div().css({ width: '100%', height: '100%',
679 position: 'absolute', zIndex: zIndex + 2 || 2 });
681 $box.add($outer).css({ visibility: 'hidden', position: position,
682 overflow: 'hidden', zIndex: zIndex || '0' });
683 $box.css({ zIndex: zIndex + 2 || 2 });
684 $area.add($border).css({ position: 'absolute', fontSize: 0 });
686 img.complete || img.readyState == 'complete' || !$img.is('img') ?
687 imgLoad() : $img.one('load', imgLoad);
690 $.fn.imgAreaSelect = function (options) {
691 options = options || {};
693 this.each(function () {
694 if ($(this).data('imgAreaSelect')) {
695 if (options.remove) {
696 $(this).data('imgAreaSelect').remove();
697 $(this).removeData('imgAreaSelect');
700 $(this).data('imgAreaSelect').setOptions(options);
702 else if (!options.remove) {
703 if (options.enable === undefined && options.disable === undefined)
704 options.enable = true;
706 $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
710 if (options.instance)
711 return $(this).data('imgAreaSelect');