2
* jquery.Jcrop.js v0.9.8
3
* jQuery Image Cropping Plugin
4
* @author Kelly Hallman <khallman@gmail.com>
5
* Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{
7
* Permission is hereby granted, free of charge, to any person
8
* obtaining a copy of this software and associated documentation
9
* files (the "Software"), to deal in the Software without
10
* restriction, including without limitation the rights to use,
11
* copy, modify, merge, publish, distribute, sublicense, and/or sell
12
* copies of the Software, and to permit persons to whom the
13
* Software is furnished to do so, subject to the following
16
* The above copyright notice and this permission notice shall be
17
* included in all copies or substantial portions of the Software.
19
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
23
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
24
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
26
* OTHER DEALINGS IN THE SOFTWARE.
33
$.Jcrop = function(obj,opt)
37
// Sanitize some options {{{
38
var obj = obj, opt = opt;
40
if (typeof(obj) !== 'object') obj = $(obj)[0];
41
if (typeof(opt) !== 'object') opt = { };
43
// Some on-the-fly fixes for MSIE...sigh
44
if (!('trackDocument' in opt))
46
opt.trackDocument = $.browser.msie ? false : true;
47
if ($.browser.msie && $.browser.version.split('.')[0] == '8')
48
opt.trackDocument = true;
51
if (!('keySupport' in opt))
52
opt.keySupport = $.browser.msie ? false : true;
55
// Extend the default options {{{
96
// Callbacks / Event Handlers
97
onChange: function() { },
98
onSelect: function() { }
101
var options = defaults;
105
// Initialize some jQuery objects {{{
107
var $origimg = $(obj);
108
var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' });
110
$img.width($origimg.width());
111
$img.height($origimg.height());
112
$origimg.after($img).hide();
114
presize($img,options.boxWidth,options.boxHeight);
116
var boundx = $img.width(),
117
boundy = $img.height(),
120
.width(boundx).height(boundy)
121
.addClass(cssClass('holder'))
123
position: 'relative',
124
backgroundColor: options.bgColor
125
}).insertAfter($origimg).append($img);
128
if (options.addClass) $div.addClass(options.addClass);
131
var $img2 = $('<img />')/*{{{*/
132
.attr('src',$img.attr('src'))
133
.css('position','absolute')
134
.width(boundx).height(boundy)
136
var $img_holder = $('<div />')/*{{{*/
137
.width(pct(100)).height(pct(100))
140
position: 'absolute',
145
var $hdl_holder = $('<div />')/*{{{*/
146
.width(pct(100)).height(pct(100))
149
var $sel = $('<div />')/*{{{*/
151
position: 'absolute',
155
.append($img_holder,$hdl_holder)
158
var bound = options.boundary;
159
var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2))
160
.css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 })
161
.mousedown(newSelection);
164
// Set more variables {{{
166
var xlimit, ylimit, xmin, ymin;
167
var xscale, yscale, enabled = true;
168
var docOffset = getPos($img),
170
btndown, lastcurs, dimmed, animating,
177
// Internal Modules {{{
179
var Coords = function()/*{{{*/
181
var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy;
183
function setPressed(pos)/*{{{*/
185
var pos = rebound(pos);
190
function setCurrent(pos)/*{{{*/
192
var pos = rebound(pos);
199
function getOffset()/*{{{*/
204
function moveOffset(offset)/*{{{*/
206
var ox = offset[0], oy = offset[1];
208
if (0 > x1 + ox) ox -= ox + x1;
209
if (0 > y1 + oy) oy -= oy + y1;
211
if (boundy < y2 + oy) oy += boundy - (y2 + oy);
212
if (boundx < x2 + ox) ox += boundx - (x2 + ox);
220
function getCorner(ord)/*{{{*/
225
case 'ne': return [ c.x2, c.y ];
226
case 'nw': return [ c.x, c.y ];
227
case 'se': return [ c.x2, c.y2 ];
228
case 'sw': return [ c.x, c.y2 ];
232
function getFixed()/*{{{*/
234
if (!options.aspectRatio) return getRect();
235
// This function could use some optimization I think...
236
var aspect = options.aspectRatio,
237
min_x = options.minSize[0]/xscale,
238
min_y = options.minSize[1]/yscale,
239
max_x = options.maxSize[0]/xscale,
240
max_y = options.maxSize[1]/yscale,
245
real_ratio = rwa / rha,
248
if (max_x == 0) { max_x = boundx * 10 }
249
if (max_y == 0) { max_y = boundy * 10 }
250
if (real_ratio < aspect)
254
xx = rw < 0 ? x1 - w : w + x1;
259
h = Math.abs((xx - x1) / aspect);
260
yy = rh < 0 ? y1 - h: h + y1;
262
else if (xx > boundx)
265
h = Math.abs((xx - x1) / aspect);
266
yy = rh < 0 ? y1 - h : h + y1;
273
yy = rh < 0 ? y1 - h : y1 + h;
277
w = Math.abs((yy - y1) * aspect);
278
xx = rw < 0 ? x1 - w : w + x1;
280
else if (yy > boundy)
283
w = Math.abs(yy - y1) * aspect;
284
xx = rw < 0 ? x1 - w : w + x1;
289
if(xx > x1) { // right side
290
if(xx - x1 < min_x) {
292
} else if (xx - x1 > max_x) {
296
yy = y1 + (xx - x1)/aspect;
298
yy = y1 - (xx - x1)/aspect;
300
} else if (xx < x1) { // left side
301
if(x1 - xx < min_x) {
303
} else if (x1 - xx > max_x) {
307
yy = y1 + (x1 - xx)/aspect;
309
yy = y1 - (x1 - xx)/aspect;
316
} else if (xx > boundx) {
324
} else if (yy > boundy) {
329
return last = makeObj(flipCoords(x1,y1,xx,yy));
332
function rebound(p)/*{{{*/
334
if (p[0] < 0) p[0] = 0;
335
if (p[1] < 0) p[1] = 0;
337
if (p[0] > boundx) p[0] = boundx;
338
if (p[1] > boundy) p[1] = boundy;
340
return [ p[0], p[1] ];
343
function flipCoords(x1,y1,x2,y2)/*{{{*/
345
var xa = x1, xb = x2, ya = y1, yb = y2;
356
return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ];
359
function getRect()/*{{{*/
364
if (xlimit && (Math.abs(xsize) > xlimit))
365
x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit);
366
if (ylimit && (Math.abs(ysize) > ylimit))
367
y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit);
369
if (ymin && (Math.abs(ysize) < ymin))
370
y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin);
371
if (xmin && (Math.abs(xsize) < xmin))
372
x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin);
374
if (x1 < 0) { x2 -= x1; x1 -= x1; }
375
if (y1 < 0) { y2 -= y1; y1 -= y1; }
376
if (x2 < 0) { x1 -= x2; x2 -= x2; }
377
if (y2 < 0) { y1 -= y2; y2 -= y2; }
378
if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; }
379
if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; }
380
if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; }
381
if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; }
383
return makeObj(flipCoords(x1,y1,x2,y2));
386
function makeObj(a)/*{{{*/
388
return { x: a[0], y: a[1], x2: a[2], y2: a[3],
389
w: a[2] - a[0], h: a[3] - a[1] };
394
flipCoords: flipCoords,
395
setPressed: setPressed,
396
setCurrent: setCurrent,
397
getOffset: getOffset,
398
moveOffset: moveOffset,
399
getCorner: getCorner,
405
var Selection = function()/*{{{*/
407
var start, end, dragmode, awake, hdep = 370;
410
var seehandles = false;
411
var hhs = options.handleOffset;
413
/* Insert draggable elements {{{*/
415
// Insert border divs for outline
416
if (options.drawBorders) {
418
top: insertBorder('hline')
419
.css('top',$.browser.msie?px(-1):px(0)),
420
bottom: insertBorder('hline'),
421
left: insertBorder('vline'),
422
right: insertBorder('vline')
426
// Insert handles on edges
427
if (options.dragEdges) {
428
handle.t = insertDragbar('n');
429
handle.b = insertDragbar('s');
430
handle.r = insertDragbar('e');
431
handle.l = insertDragbar('w');
434
// Insert side handles
435
options.sideHandles &&
436
createHandles(['n','s','e','w']);
438
// Insert corner handles
439
options.cornerHandles &&
440
createHandles(['sw','nw','ne','se']);
444
function insertBorder(type)/*{{{*/
446
var jq = $('<div />')
447
.css({position: 'absolute', opacity: options.borderOpacity })
448
.addClass(cssClass(type));
449
$img_holder.append(jq);
453
function dragDiv(ord,zi)/*{{{*/
455
var jq = $('<div />')
456
.mousedown(createDragger(ord))
458
cursor: ord+'-resize',
459
position: 'absolute',
463
$hdl_holder.append(jq);
467
function insertHandle(ord)/*{{{*/
469
return dragDiv(ord,hdep++)
470
.css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity })
471
.addClass(cssClass('handle'));
474
function insertDragbar(ord)/*{{{*/
476
var s = options.handleSize,
483
case 'n': case 's': w = pct(100); break;
484
case 'e': case 'w': h = pct(100); break;
487
return dragDiv(ord,hdep++).width(w).height(h)
488
.css({ top: px(-t+1), left: px(-l+1)});
491
function createHandles(li)/*{{{*/
493
for(i in li) handle[li[i]] = insertHandle(li[i]);
496
function moveHandles(c)/*{{{*/
498
var midvert = Math.round((c.h / 2) - hhs),
499
midhoriz = Math.round((c.w / 2) - hhs),
500
north = west = -hhs+1,
506
handle.e.css({ top: px(midvert), left: px(east) }) &&
507
handle.w.css({ top: px(midvert) }) &&
508
handle.s.css({ top: px(south), left: px(midhoriz) }) &&
509
handle.n.css({ left: px(midhoriz) });
512
handle.ne.css({ left: px(east) }) &&
513
handle.se.css({ top: px(south), left: px(east) }) &&
514
handle.sw.css({ top: px(south) });
517
handle.b.css({ top: px(south) }) &&
518
handle.r.css({ left: px(east) });
521
function moveto(x,y)/*{{{*/
523
$img2.css({ top: px(-y), left: px(-x) });
524
$sel.css({ top: px(y), left: px(x) });
527
function resize(w,h)/*{{{*/
529
$sel.width(w).height(h);
532
function refresh()/*{{{*/
534
var c = Coords.getFixed();
536
Coords.setPressed([c.x,c.y]);
537
Coords.setCurrent([c.x2,c.y2]);
544
function updateVisible()/*{{{*/
545
{ if (awake) return update(); };
547
function update()/*{{{*/
549
var c = Coords.getFixed();
554
options.drawBorders &&
555
borders['right'].css({ left: px(c.w-1) }) &&
556
borders['bottom'].css({ top: px(c.h-1) });
558
seehandles && moveHandles(c);
561
options.onChange(unscale(c));
564
function show()/*{{{*/
567
$img.css('opacity',options.bgOpacity);
571
function release()/*{{{*/
575
$img.css('opacity',1);
579
function showHandles()//{{{
583
moveHandles(Coords.getFixed());
588
function enableHandles()/*{{{*/
591
if (options.allowResize)
593
moveHandles(Coords.getFixed());
599
function disableHandles()/*{{{*/
605
function animMode(v)/*{{{*/
607
(animating = v) ? disableHandles(): enableHandles();
610
function done()/*{{{*/
617
var $track = newTracker().mousedown(createDragger('move'))
618
.css({ cursor: 'move', position: 'absolute', zIndex: 360 })
620
$img_holder.append($track);
624
updateVisible: updateVisible,
628
setCursor: function (cursor) { $track.css('cursor',cursor); },
629
enableHandles: enableHandles,
630
enableOnly: function() { seehandles = true; },
631
showHandles: showHandles,
632
disableHandles: disableHandles,
638
var Tracker = function()/*{{{*/
640
var onMove = function() { },
641
onDone = function() { },
642
trackDoc = options.trackDocument;
647
.mousemove(trackMove)
653
function toFront()/*{{{*/
655
$trk.css({zIndex:450});
659
.mousemove(trackMove)
665
function toBack()/*{{{*/
667
$trk.css({zIndex:290});
671
.unbind('mousemove',trackMove)
672
.unbind('mouseup',trackUp)
677
function trackMove(e)/*{{{*/
682
function trackUp(e)/*{{{*/
692
options.onSelect(unscale(Coords.getFixed()));
694
onMove = function() { };
695
onDone = function() { };
702
function activateHandlers(move,done)/* {{{ */
712
function setCursor(t) { $trk.css('cursor',t); };
716
activateHandlers: activateHandlers,
721
var KeyManager = function()/*{{{*/
723
var $keymgr = $('<input type="radio" />')
724
.css({ position: 'absolute', left: '-30px' })
728
$keywrap = $('<div />')
730
position: 'absolute',
736
function watchKeys()/*{{{*/
738
if (options.keySupport)
745
function onBlur(e)/*{{{*/
750
function doNudge(e,x,y)/*{{{*/
752
if (options.allowMove) {
753
Coords.moveOffset([x,y]);
754
Selection.updateVisible();
760
function parseKey(e)/*{{{*/
762
if (e.ctrlKey) return true;
763
shift_down = e.shiftKey ? true : false;
764
var nudge = shift_down ? 10 : 1;
767
case 37: doNudge(e,-nudge,0); break;
768
case 39: doNudge(e,nudge,0); break;
769
case 38: doNudge(e,0,-nudge); break;
770
case 40: doNudge(e,0,nudge); break;
772
case 27: Selection.release(); break;
781
if (options.keySupport) $keywrap.insertBefore($img);
789
// Internal Methods {{{
791
function px(n) { return '' + parseInt(n) + 'px'; };
792
function pct(n) { return '' + parseInt(n) + '%'; };
793
function cssClass(cl) { return options.baseClass + '-' + cl; };
794
function getPos(obj)/*{{{*/
796
// Updated in v0.9.4 to use built-in dimensions plugin
797
var pos = $(obj).offset();
798
return [ pos.left, pos.top ];
801
function mouseAbs(e)/*{{{*/
803
return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ];
806
function myCursor(type)/*{{{*/
808
if (type != lastcurs)
810
Tracker.setCursor(type);
811
//Handles.xsetCursor(type);
816
function startDragMode(mode,pos)/*{{{*/
818
docOffset = getPos($img);
819
Tracker.setCursor(mode=='move'?mode:mode+'-resize');
822
return Tracker.activateHandlers(createMover(pos), doneSelect);
824
var fc = Coords.getFixed();
825
var opp = oppLockCorner(mode);
826
var opc = Coords.getCorner(oppLockCorner(opp));
828
Coords.setPressed(Coords.getCorner(opp));
829
Coords.setCurrent(opc);
831
Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect);
834
function dragmodeHandler(mode,f)/*{{{*/
836
return function(pos) {
837
if (!options.aspectRatio) switch(mode)
839
case 'e': pos[1] = f.y2; break;
840
case 'w': pos[1] = f.y2; break;
841
case 'n': pos[0] = f.x2; break;
842
case 's': pos[0] = f.x2; break;
846
case 'e': pos[1] = f.y+1; break;
847
case 'w': pos[1] = f.y+1; break;
848
case 'n': pos[0] = f.x+1; break;
849
case 's': pos[0] = f.x+1; break;
851
Coords.setCurrent(pos);
856
function createMover(pos)/*{{{*/
859
KeyManager.watchKeys();
863
Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
870
function oppLockCorner(ord)/*{{{*/
874
case 'n': return 'sw';
875
case 's': return 'nw';
876
case 'e': return 'nw';
877
case 'w': return 'ne';
878
case 'ne': return 'sw';
879
case 'nw': return 'se';
880
case 'se': return 'nw';
881
case 'sw': return 'ne';
885
function createDragger(ord)/*{{{*/
888
if (options.disabled) return false;
889
if ((ord == 'move') && !options.allowMove) return false;
891
startDragMode(ord,mouseAbs(e));
898
function presize($obj,w,h)/*{{{*/
900
var nw = $obj.width(), nh = $obj.height();
901
if ((nw > w) && w > 0)
904
nh = (w/$obj.width()) * $obj.height();
906
if ((nh > h) && h > 0)
909
nw = (h/$obj.height()) * $obj.width();
911
xscale = $obj.width() / nw;
912
yscale = $obj.height() / nh;
913
$obj.width(nw).height(nh);
916
function unscale(c)/*{{{*/
919
x: parseInt(c.x * xscale), y: parseInt(c.y * yscale),
920
x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale),
921
w: parseInt(c.w * xscale), h: parseInt(c.h * yscale)
925
function doneSelect(pos)/*{{{*/
927
var c = Coords.getFixed();
928
if (c.w > options.minSelect[0] && c.h > options.minSelect[1])
930
Selection.enableHandles();
937
Tracker.setCursor( options.allowSelect?'crosshair':'default' );
940
function newSelection(e)/*{{{*/
942
if (options.disabled) return false;
943
if (!options.allowSelect) return false;
945
docOffset = getPos($img);
946
Selection.disableHandles();
947
myCursor('crosshair');
948
var pos = mouseAbs(e);
949
Coords.setPressed(pos);
950
Tracker.activateHandlers(selectDrag,doneSelect);
951
KeyManager.watchKeys();
959
function selectDrag(pos)/*{{{*/
961
Coords.setCurrent(pos);
965
function newTracker()
967
var trk = $('<div></div>').addClass(cssClass('tracker'));
968
$.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' });
975
function animateTo(a)/*{{{*/
977
var x1 = a[0] / xscale,
982
if (animating) return;
984
var animto = Coords.flipCoords(x1,y1,x2,y2);
985
var c = Coords.getFixed();
986
var animat = initcr = [ c.x, c.y, c.x2, c.y2 ];
987
var interv = options.animationDelay;
993
var ix1 = animto[0] - initcr[0];
994
var iy1 = animto[1] - initcr[1];
995
var ix2 = animto[2] - initcr[2];
996
var iy2 = animto[3] - initcr[3];
998
var velocity = options.swingSpeed;
1000
Selection.animMode(true);
1002
var animator = function()
1006
pcent += (100 - pcent) / velocity;
1008
animat[0] = x + ((pcent / 100) * ix1);
1009
animat[1] = y + ((pcent / 100) * iy1);
1010
animat[2] = x2 + ((pcent / 100) * ix2);
1011
animat[3] = y2 + ((pcent / 100) * iy2);
1013
if (pcent < 100) animateStart();
1014
else Selection.done();
1016
if (pcent >= 99.8) pcent = 100;
1018
setSelectRaw(animat);
1022
function animateStart()
1023
{ window.setTimeout(animator,interv); };
1028
function setSelect(rect)//{{{
1030
setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]);
1033
function setSelectRaw(l) /*{{{*/
1035
Coords.setPressed([l[0],l[1]]);
1036
Coords.setCurrent([l[2],l[3]]);
1040
function setOptions(opt)/*{{{*/
1042
if (typeof(opt) != 'object') opt = { };
1043
options = $.extend(options,opt);
1045
if (typeof(options.onChange)!=='function')
1046
options.onChange = function() { };
1048
if (typeof(options.onSelect)!=='function')
1049
options.onSelect = function() { };
1053
function tellSelect()/*{{{*/
1055
return unscale(Coords.getFixed());
1058
function tellScaled()/*{{{*/
1060
return Coords.getFixed();
1063
function setOptionsNew(opt)/*{{{*/
1069
function disableCrop()//{{{
1071
options.disabled = true;
1072
Selection.disableHandles();
1073
Selection.setCursor('default');
1074
Tracker.setCursor('default');
1077
function enableCrop()//{{{
1079
options.disabled = false;
1083
function cancelCrop()//{{{
1086
Tracker.activateHandlers(null,null);
1089
function destroy()//{{{
1096
function interfaceUpdate(alt)//{{{
1097
// This method tweaks the interface based on options object.
1098
// Called when options are changed and at end of initialization.
1100
options.allowResize ?
1101
alt?Selection.enableOnly():Selection.enableHandles():
1102
Selection.disableHandles();
1104
Tracker.setCursor( options.allowSelect? 'crosshair': 'default' );
1105
Selection.setCursor( options.allowMove? 'move': 'default' );
1107
$div.css('backgroundColor',options.bgColor);
1109
if ('setSelect' in options) {
1110
setSelect(opt.setSelect);
1112
delete(options.setSelect);
1115
if ('trueSize' in options) {
1116
xscale = options.trueSize[0] / boundx;
1117
yscale = options.trueSize[1] / boundy;
1120
xlimit = options.maxSize[0] || 0;
1121
ylimit = options.maxSize[1] || 0;
1122
xmin = options.minSize[0] || 0;
1123
ymin = options.minSize[1] || 0;
1125
if ('outerImage' in options)
1127
$img.attr('src',options.outerImage);
1128
delete(options.outerImage);
1131
Selection.refresh();
1138
interfaceUpdate(true);
1141
animateTo: animateTo,
1142
setSelect: setSelect,
1143
setOptions: setOptionsNew,
1144
tellSelect: tellSelect,
1145
tellScaled: tellScaled,
1147
disable: disableCrop,
1151
focus: KeyManager.watchKeys,
1153
getBounds: function() { return [ boundx * xscale, boundy * yscale ]; },
1154
getWidgetSize: function() { return [ boundx, boundy ]; },
1156
release: Selection.release,
1161
$origimg.data('Jcrop',api);
1165
$.fn.Jcrop = function(options)/*{{{*/
1167
function attachWhenDone(from)/*{{{*/
1169
var loadsrc = options.useImg || from.src;
1170
var img = new Image();
1171
img.onload = function() { $.Jcrop(from,options); };
1175
if (typeof(options) !== 'object') options = { };
1177
// Iterate over each object, attach Jcrop
1178
this.each(function()
1180
// If we've already attached to this object
1181
if ($(this).data('Jcrop'))
1183
// The API can be requested this way (undocumented)
1184
if (options == 'api') return $(this).data('Jcrop');
1185
// Otherwise, we just reset the options...
1186
else $(this).data('Jcrop').setOptions(options);
1188
// If we haven't been attached, preload and attach
1189
else attachWhenDone(this);
1192
// Return "this" so we're chainable a la jQuery plugin-style!