2 * imgAreaSelect jQuery plugin
5 * Copyright (c) 2008-2013 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()),
42 imgOfs = { left: 0, top: 0 },
48 parOfs = { left: 0, top: 0 },
52 position = 'absolute',
60 minWidth, minHeight, maxWidth, maxHeight,
68 selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
70 docElem = document.documentElement,
72 ua = navigator.userAgent,
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;
115 x1: round(x1 / sx || 0),
116 y1: round(y1 / sy || 0),
117 x2: round(x2 / sx || 0),
118 y2: round(y2 / sy || 0)
121 selection.width = selection.x2 - selection.x1;
122 selection.height = selection.y2 - selection.y1;
126 if (!imgLoaded || !$img.width())
129 imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
131 imgWidth = $img.innerWidth();
132 imgHeight = $img.innerHeight();
134 imgOfs.top += ($img.outerHeight() - imgHeight) >> 1;
135 imgOfs.left += ($img.outerWidth() - imgWidth) >> 1;
137 minWidth = round(options.minWidth / scaleX) || 0;
138 minHeight = round(options.minHeight / scaleY) || 0;
139 maxWidth = round(min(options.maxWidth / scaleX || 1<<24, imgWidth));
140 maxHeight = round(min(options.maxHeight / scaleY || 1<<24, imgHeight));
142 if ($().jquery == '1.3.2' && position == 'fixed' &&
143 !docElem['getBoundingClientRect'])
145 imgOfs.top += max(document.body.scrollTop, docElem.scrollTop);
146 imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft);
149 parOfs = /absolute|relative/.test($parent.css('position')) ?
150 { left: round($parent.offset().left) - $parent.scrollLeft(),
151 top: round($parent.offset().top) - $parent.scrollTop() } :
152 position == 'fixed' ?
153 { left: $(document).scrollLeft(), top: $(document).scrollTop() } :
159 if (selection.x2 > imgWidth || selection.y2 > imgHeight)
163 function update(resetKeyPress) {
166 $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
167 .add($area).width(w = selection.width).height(h = selection.height);
169 $area.add($border).add($handles).css({ left: 0, top: 0 });
172 .width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
173 .height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
175 $($outer[0]).css({ left: left, top: top,
176 width: selection.x1, height: imgHeight });
177 $($outer[1]).css({ left: left + selection.x1, top: top,
178 width: w, height: selection.y1 });
179 $($outer[2]).css({ left: left + selection.x2, top: top,
180 width: imgWidth - selection.x2, height: imgHeight });
181 $($outer[3]).css({ left: left + selection.x1, top: top + selection.y2,
182 width: w, height: imgHeight - selection.y2 });
184 w -= $handles.outerWidth();
185 h -= $handles.outerHeight();
187 switch ($handles.length) {
189 $($handles[4]).css({ left: w >> 1 });
190 $($handles[5]).css({ left: w, top: h >> 1 });
191 $($handles[6]).css({ left: w >> 1, top: h });
192 $($handles[7]).css({ top: h >> 1 });
194 $handles.slice(1,3).css({ left: w });
195 $handles.slice(2,4).css({ top: h });
198 if (resetKeyPress !== false) {
199 if ($.imgAreaSelect.onKeyPress != docKeyPress)
200 $(document).unbind($.imgAreaSelect.keyPress,
201 $.imgAreaSelect.onKeyPress);
204 $(document)[$.imgAreaSelect.keyPress](
205 $.imgAreaSelect.onKeyPress = docKeyPress);
208 if (msie && $border.outerWidth() - $border.innerWidth() == 2) {
209 $border.css('margin', 0);
210 setTimeout(function () { $border.css('margin', 'auto'); }, 0);
214 function doUpdate(resetKeyPress) {
216 update(resetKeyPress);
217 x1 = viewX(selection.x1); y1 = viewY(selection.y1);
218 x2 = viewX(selection.x2); y2 = viewY(selection.y2);
221 function hide($elem, fn) {
222 options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
226 function areaMouseMove(event) {
227 var x = selX(evX(event)) - selection.x1,
228 y = selY(evY(event)) - selection.y1;
234 $box.one('mouseout', function () { adjusted = false; });
239 if (options.resizable) {
240 if (y <= options.resizeMargin)
242 else if (y >= selection.height - options.resizeMargin)
244 if (x <= options.resizeMargin)
246 else if (x >= selection.width - options.resizeMargin)
250 $box.css('cursor', resize ? resize + '-resize' :
251 options.movable ? 'move' : '');
256 function docMouseUp(event) {
257 $('body').css('cursor', '');
258 if (options.autoHide || selection.width * selection.height == 0)
259 hide($box.add($outer), function () { $(this).hide(); });
261 $(document).unbind('mousemove', selectingMouseMove);
262 $box.mousemove(areaMouseMove);
264 options.onSelectEnd(img, getSelection());
267 function areaMouseDown(event) {
268 if (event.which != 1) return false;
273 $('body').css('cursor', resize + '-resize');
275 x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
276 y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
278 $(document).mousemove(selectingMouseMove)
279 .one('mouseup', docMouseUp);
280 $box.unbind('mousemove', areaMouseMove);
282 else if (options.movable) {
283 startX = left + selection.x1 - evX(event);
284 startY = top + selection.y1 - evY(event);
286 $box.unbind('mousemove', areaMouseMove);
288 $(document).mousemove(movingMouseMove)
289 .one('mouseup', function () {
290 options.onSelectEnd(img, getSelection());
292 $(document).unbind('mousemove', movingMouseMove);
293 $box.mousemove(areaMouseMove);
297 $img.mousedown(event);
302 function fixAspectRatio(xFirst) {
305 x2 = max(left, min(left + imgWidth,
306 x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
308 y2 = round(max(top, min(top + imgHeight,
309 y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
313 y2 = max(top, min(top + imgHeight,
314 y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
315 x2 = round(max(left, min(left + imgWidth,
316 x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
321 function doResize() {
322 x1 = min(x1, left + imgWidth);
323 y1 = min(y1, top + imgHeight);
325 if (abs(x2 - x1) < minWidth) {
326 x2 = x1 - minWidth * (x2 < x1 || -1);
329 x1 = left + minWidth;
330 else if (x2 > left + imgWidth)
331 x1 = left + imgWidth - minWidth;
334 if (abs(y2 - y1) < minHeight) {
335 y2 = y1 - minHeight * (y2 < y1 || -1);
338 y1 = top + minHeight;
339 else if (y2 > top + imgHeight)
340 y1 = top + imgHeight - minHeight;
343 x2 = max(left, min(x2, left + imgWidth));
344 y2 = max(top, min(y2, top + imgHeight));
346 fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio);
348 if (abs(x2 - x1) > maxWidth) {
349 x2 = x1 - maxWidth * (x2 < x1 || -1);
353 if (abs(y2 - y1) > maxHeight) {
354 y2 = y1 - maxHeight * (y2 < y1 || -1);
355 fixAspectRatio(true);
358 selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
359 y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
360 width: abs(x2 - x1), height: abs(y2 - y1) };
364 options.onSelectChange(img, getSelection());
367 function selectingMouseMove(event) {
368 x2 = /w|e|^$/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
369 y2 = /n|s|^$/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
377 function doMove(newX1, newY1) {
378 x2 = (x1 = newX1) + selection.width;
379 y2 = (y1 = newY1) + selection.height;
381 $.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2),
386 options.onSelectChange(img, getSelection());
389 function movingMouseMove(event) {
390 x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
391 y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
395 event.preventDefault();
400 function startSelection() {
401 $(document).unbind('mousemove', startSelection);
411 if (!$outer.is(':visible'))
412 $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
416 $(document).unbind('mouseup', cancelSelection)
417 .mousemove(selectingMouseMove).one('mouseup', docMouseUp);
418 $box.unbind('mousemove', areaMouseMove);
420 options.onSelectStart(img, getSelection());
423 function cancelSelection() {
424 $(document).unbind('mousemove', startSelection)
425 .unbind('mouseup', cancelSelection);
426 hide($box.add($outer));
428 setSelection(selX(x1), selY(y1), selX(x1), selY(y1));
430 if (!(this instanceof $.imgAreaSelect)) {
431 options.onSelectChange(img, getSelection());
432 options.onSelectEnd(img, getSelection());
436 function imgMouseDown(event) {
437 if (event.which != 1 || $outer.is(':animated')) return false;
440 startX = x1 = evX(event);
441 startY = y1 = evY(event);
443 $(document).mousemove(startSelection).mouseup(cancelSelection);
448 function windowResize() {
455 setOptions(options = $.extend({
456 classPrefix: 'imgareaselect',
461 onInit: function () {},
462 onSelectStart: function () {},
463 onSelectChange: function () {},
464 onSelectEnd: function () {}
467 $box.add($outer).css({ visibility: '' });
473 $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
476 setTimeout(function () { options.onInit(img, getSelection()); }, 0);
479 var docKeyPress = function(event) {
480 var k = options.keys, d, t, key = event.keyCode;
482 d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
483 !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
484 !isNaN(k.shift) && event.shiftKey ? k.shift :
485 !isNaN(k.arrows) ? k.arrows : 10;
487 if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
488 (k.ctrl == 'resize' && event.ctrlKey) ||
489 (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
506 fixAspectRatio(true);
520 doMove(max(x1 - d, left), y1);
523 doMove(x1, max(y1 - d, top));
526 doMove(x1 + min(d, imgWidth - selX(x2)), y1);
529 doMove(x1, y1 + min(d, imgHeight - selY(y2)));
539 function styleOptions($elem, props) {
540 for (var option in props)
541 if (options[option] !== undefined)
542 $elem.css(props[option], options[option]);
545 function setOptions(newOptions) {
546 if (newOptions.parent)
547 ($parent = $(newOptions.parent)).append($box.add($outer));
549 $.extend(options, newOptions);
553 if (newOptions.handles != null) {
557 i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
560 $handles = $handles.add(div());
562 $handles.addClass(options.classPrefix + '-handle').css({
563 position: 'absolute',
565 zIndex: zIndex + 1 || 1
568 if (!parseInt($handles.css('width')) >= 0)
569 $handles.width(5).height(5);
571 if (o = options.borderWidth)
572 $handles.css({ borderWidth: o, borderStyle: 'solid' });
574 styleOptions($handles, { borderColor1: 'border-color',
575 borderColor2: 'background-color',
576 borderOpacity: 'opacity' });
579 scaleX = options.imageWidth / imgWidth || 1;
580 scaleY = options.imageHeight / imgHeight || 1;
582 if (newOptions.x1 != null) {
583 setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
585 newOptions.show = !newOptions.hide;
589 options.keys = $.extend({ shift: 1, ctrl: 'resize' },
592 $outer.addClass(options.classPrefix + '-outer');
593 $area.addClass(options.classPrefix + '-selection');
594 for (i = 0; i++ < 4;)
595 $($border[i-1]).addClass(options.classPrefix + '-border' + i);
597 styleOptions($area, { selectionColor: 'background-color',
598 selectionOpacity: 'opacity' });
599 styleOptions($border, { borderOpacity: 'opacity',
600 borderWidth: 'border-width' });
601 styleOptions($outer, { outerColor: 'background-color',
602 outerOpacity: 'opacity' });
603 if (o = options.borderColor1)
604 $($border[0]).css({ borderStyle: 'solid', borderColor: o });
605 if (o = options.borderColor2)
606 $($border[1]).css({ borderStyle: 'dashed', borderColor: o });
608 $box.append($area.add($border).add($areaOpera)).append($handles);
611 if (o = ($outer.css('filter')||'').match(/opacity=(\d+)/))
612 $outer.css('opacity', o[1]/100);
613 if (o = ($border.css('filter')||'').match(/opacity=(\d+)/))
614 $border.css('opacity', o[1]/100);
618 hide($box.add($outer));
619 else if (newOptions.show && imgLoaded) {
621 $box.add($outer).fadeIn(options.fadeSpeed||0);
625 aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
627 $img.add($outer).unbind('mousedown', imgMouseDown);
629 if (options.disable || options.enable === false) {
630 $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown);
631 $(window).unbind('resize', windowResize);
634 if (options.enable || options.disable === false) {
635 if (options.resizable || options.movable)
636 $box.mousemove(areaMouseMove).mousedown(areaMouseDown);
638 $(window).resize(windowResize);
641 if (!options.persistent)
642 $img.add($outer).mousedown(imgMouseDown);
645 options.enable = options.disable = undefined;
648 this.remove = function () {
649 setOptions({ disable: true });
650 $box.add($outer).remove();
653 this.getOptions = function () { return options; };
655 this.setOptions = setOptions;
657 this.getSelection = getSelection;
659 this.setSelection = setSelection;
661 this.cancelSelection = cancelSelection;
663 this.update = doUpdate;
665 var msie = (/msie ([\w.]+)/i.exec(ua)||[])[1],
666 opera = /opera/i.test(ua),
667 safari = /webkit/i.test(ua) && !/chrome/i.test(ua);
673 !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
674 if ($p.css('position') == 'fixed')
677 $p = $p.parent(':not(body)');
680 zIndex = options.zIndex || zIndex;
683 $img.attr('unselectable', 'on');
685 $.imgAreaSelect.keyPress = msie || safari ? 'keydown' : 'keypress';
689 $areaOpera = div().css({ width: '100%', height: '100%',
690 position: 'absolute', zIndex: zIndex + 2 || 2 });
692 $box.add($outer).css({ visibility: 'hidden', position: position,
693 overflow: 'hidden', zIndex: zIndex || '0' });
694 $box.css({ zIndex: zIndex + 2 || 2 });
695 $area.add($border).css({ position: 'absolute', fontSize: 0 });
697 img.complete || img.readyState == 'complete' || !$img.is('img') ?
698 imgLoad() : $img.one('load', imgLoad);
700 if (!imgLoaded && msie && msie >= 7)
704 $.fn.imgAreaSelect = function (options) {
705 options = options || {};
707 this.each(function () {
708 if ($(this).data('imgAreaSelect')) {
709 if (options.remove) {
710 $(this).data('imgAreaSelect').remove();
711 $(this).removeData('imgAreaSelect');
714 $(this).data('imgAreaSelect').setOptions(options);
716 else if (!options.remove) {
717 if (options.enable === undefined && options.disable === undefined)
718 options.enable = true;
720 $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
724 if (options.instance)
725 return $(this).data('imgAreaSelect');