2 * imgAreaSelect jQuery plugin
5 * Copyright (c) 2008-2011 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',
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;
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;
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 = options.minWidth || 0;
138 minHeight = options.minHeight || 0;
139 maxWidth = min(options.maxWidth || 1<<24, imgWidth);
140 maxHeight = min(options.maxHeight || 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 = $.inArray($parent.css('position'), ['absolute', 'relative']) + 1 ?
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.keyPress != docKeyPress)
200 $(document).unbind($.imgAreaSelect.keyPress,
201 $.imgAreaSelect.onKeyPress);
204 $(document)[$.imgAreaSelect.keyPress](
205 $.imgAreaSelect.onKeyPress = docKeyPress);
208 if ($.browser.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 = resize == '' || /w|e/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
369 y2 = resize == '' || /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(':not(: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 options.onSelectChange(img, getSelection());
431 options.onSelectEnd(img, getSelection());
434 function imgMouseDown(event) {
435 if (event.which != 1 || $outer.is(':animated')) return false;
438 startX = x1 = evX(event);
439 startY = y1 = evY(event);
441 $(document).mousemove(startSelection).mouseup(cancelSelection);
446 function windowResize() {
453 setOptions(options = $.extend({
454 classPrefix: 'imgareaselect',
459 onInit: function () {},
460 onSelectStart: function () {},
461 onSelectChange: function () {},
462 onSelectEnd: function () {}
465 $box.add($outer).css({ visibility: '' });
471 $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
474 setTimeout(function () { options.onInit(img, getSelection()); }, 0);
477 var docKeyPress = function(event) {
478 var k = options.keys, d, t, key = event.keyCode;
480 d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
481 !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
482 !isNaN(k.shift) && event.shiftKey ? k.shift :
483 !isNaN(k.arrows) ? k.arrows : 10;
485 if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
486 (k.ctrl == 'resize' && event.ctrlKey) ||
487 (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
504 fixAspectRatio(true);
518 doMove(max(x1 - d, left), y1);
521 doMove(x1, max(y1 - d, top));
524 doMove(x1 + min(d, imgWidth - selX(x2)), y1);
527 doMove(x1, y1 + min(d, imgHeight - selY(y2)));
537 function styleOptions($elem, props) {
538 for (option in props)
539 if (options[option] !== undefined)
540 $elem.css(props[option], options[option]);
543 function setOptions(newOptions) {
544 if (newOptions.parent)
545 ($parent = $(newOptions.parent)).append($box.add($outer));
547 $.extend(options, newOptions);
551 if (newOptions.handles != null) {
555 i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
558 $handles = $handles.add(div());
560 $handles.addClass(options.classPrefix + '-handle').css({
561 position: 'absolute',
563 zIndex: zIndex + 1 || 1
566 if (!parseInt($handles.css('width')) >= 0)
567 $handles.width(5).height(5);
569 if (o = options.borderWidth)
570 $handles.css({ borderWidth: o, borderStyle: 'solid' });
572 styleOptions($handles, { borderColor1: 'border-color',
573 borderColor2: 'background-color',
574 borderOpacity: 'opacity' });
577 scaleX = options.imageWidth / imgWidth || 1;
578 scaleY = options.imageHeight / imgHeight || 1;
580 if (newOptions.x1 != null) {
581 setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
583 newOptions.show = !newOptions.hide;
587 options.keys = $.extend({ shift: 1, ctrl: 'resize' },
590 $outer.addClass(options.classPrefix + '-outer');
591 $area.addClass(options.classPrefix + '-selection');
592 for (i = 0; i++ < 4;)
593 $($border[i-1]).addClass(options.classPrefix + '-border' + i);
595 styleOptions($area, { selectionColor: 'background-color',
596 selectionOpacity: 'opacity' });
597 styleOptions($border, { borderOpacity: 'opacity',
598 borderWidth: 'border-width' });
599 styleOptions($outer, { outerColor: 'background-color',
600 outerOpacity: 'opacity' });
601 if (o = options.borderColor1)
602 $($border[0]).css({ borderStyle: 'solid', borderColor: o });
603 if (o = options.borderColor2)
604 $($border[1]).css({ borderStyle: 'dashed', borderColor: o });
606 $box.append($area.add($border).add($areaOpera).add($handles));
608 if ($.browser.msie) {
609 if (o = $outer.css('filter').match(/opacity=([0-9]+)/))
610 $outer.css('opacity', o[1]/100);
611 if (o = $border.css('filter').match(/opacity=([0-9]+)/))
612 $border.css('opacity', o[1]/100);
616 hide($box.add($outer));
617 else if (newOptions.show && imgLoaded) {
619 $box.add($outer).fadeIn(options.fadeSpeed||0);
623 aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
625 $img.add($outer).unbind('mousedown', imgMouseDown);
627 if (options.disable || options.enable === false) {
628 $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown);
629 $(window).unbind('resize', windowResize);
632 if (options.enable || options.disable === false) {
633 if (options.resizable || options.movable)
634 $box.mousemove(areaMouseMove).mousedown(areaMouseDown);
636 $(window).resize(windowResize);
639 if (!options.persistent)
640 $img.add($outer).mousedown(imgMouseDown);
643 options.enable = options.disable = undefined;
646 this.remove = function () {
647 setOptions({ disable: true });
648 $box.add($outer).remove();
651 this.getOptions = function () { return options; };
653 this.setOptions = setOptions;
655 this.getSelection = getSelection;
657 this.setSelection = setSelection;
659 this.update = doUpdate;
665 !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
666 if ($p.css('position') == 'fixed')
669 $p = $p.parent(':not(body)');
672 zIndex = options.zIndex || zIndex;
675 $img.attr('unselectable', 'on');
677 $.imgAreaSelect.keyPress = $.browser.msie ||
678 $.browser.safari ? 'keydown' : 'keypress';
681 $areaOpera = div().css({ width: '100%', height: '100%',
682 position: 'absolute', zIndex: zIndex + 2 || 2 });
684 $box.add($outer).css({ visibility: 'hidden', position: position,
685 overflow: 'hidden', zIndex: zIndex || '0' });
686 $box.css({ zIndex: zIndex + 2 || 2 });
687 $area.add($border).css({ position: 'absolute', fontSize: 0 });
689 img.complete || img.readyState == 'complete' || !$img.is('img') ?
690 imgLoad() : $img.one('load', imgLoad);
692 if ($.browser.msie && $.browser.version >= 9)
696 $.fn.imgAreaSelect = function (options) {
697 options = options || {};
699 this.each(function () {
700 if ($(this).data('imgAreaSelect')) {
701 if (options.remove) {
702 $(this).data('imgAreaSelect').remove();
703 $(this).removeData('imgAreaSelect');
706 $(this).data('imgAreaSelect').setOptions(options);
708 else if (!options.remove) {
709 if (options.enable === undefined && options.disable === undefined)
710 options.enable = true;
712 $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
716 if (options.instance)
717 return $(this).data('imgAreaSelect');