2 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 * @description <p>Creates a Image Cropper control.</p>
9 * @namespace YAHOO.widget
10 * @requires yahoo, dom, dragdrop, element, event, resize
11 * @module imagecropper
14 var Dom = YAHOO.util.Dom,
15 Event = YAHOO.util.Event,
21 * @description <p>Creates a Image Cropper control.</p>
22 * @extends YAHOO.util.Element
23 * @param {String/HTMLElement} el The image element to make croppable.
24 * @param {Object} attrs Object liternal containing configuration parameters.
26 var Crop = function(el, config) {
29 attributes: config || {}
32 Crop.superclass.constructor.call(this, oConfig.element, oConfig.attributes);
38 * @property _instances
39 * @description Internal hash table for all ImageCropper instances
45 * @method getCropperById
46 * @description Get's an ImageCropper object by the HTML id of the image associated with the ImageCropper object.
47 * @return {Object} The ImageCropper Object
49 Crop.getCropperById = function(id) {
50 if (Crop._instances[id]) {
51 return Crop._instances[id];
56 YAHOO.extend(Crop, YAHOO.util.Element, {
60 * @description The CSS class used to wrap the element
67 * @description The CSS class for the mask element
70 CSS_MASK: 'yui-crop-mask',
73 * @property CSS_RESIZE_MASK
74 * @description The CSS class for the mask inside the resize element
77 CSS_RESIZE_MASK: 'yui-crop-resize-mask',
82 * @description The url of the image we are cropping
89 * @description Flag to determine if the crop region is active
96 * @description A reference to the Resize Utility used in this Cropper Instance
102 * @property _resizeEl
103 * @description The HTML Element used to create the Resize Oject
109 * @property _resizeMaskEl
110 * @description The HTML Element used to create the Resize mask
117 * @description The HTML Element created to wrap the image
124 * @description The HTML Element created to "mask" the image being cropped
130 * @method _createWrap
131 * @description Creates the wrapper element used to wrap the image
133 _createWrap: function() {
134 this._wrap = document.createElement('div');
135 this._wrap.id = this.get('element').id + '_wrap';
136 this._wrap.className = this.CSS_MAIN;
137 var el = this.get('element');
138 this._wrap.style.width = el.width ? el.width + 'px' : Dom.getStyle(el, 'width');
139 this._wrap.style.height = el.height ? el.height + 'px' : Dom.getStyle(el, 'height');
141 var par = this.get('element').parentNode;
142 par.replaceChild(this._wrap, this.get('element'));
143 this._wrap.appendChild(this.get('element'));
145 Event.on(this._wrap, 'mouseover', this._handleMouseOver, this, true);
146 Event.on(this._wrap, 'mouseout', this._handleMouseOut, this, true);
148 Event.on(this._wrap, 'click', function(ev) { Event.stopEvent(ev); }, this, true);
153 * @method _createMask
154 * @description Creates the mask element used to mask the image
156 _createMask: function() {
157 this._mask = document.createElement('div');
158 this._mask.className = this.CSS_MASK;
159 this._wrap.appendChild(this._mask);
164 * @method _createResize
165 * @description Creates the resize element and the instance of the Resize Utility
167 _createResize: function() {
168 this._resizeEl = document.createElement('div');
169 this._resizeEl.className = YAHOO.util.Resize.prototype.CSS_RESIZE;
170 this._resizeEl.style.position = 'absolute';
172 this._resizeEl.innerHTML = '<div class="' + this.CSS_RESIZE_MASK + '"></div>';
173 this._resizeMaskEl = this._resizeEl.firstChild;
174 this._wrap.appendChild(this._resizeEl);
175 this._resizeEl.style.top = this.get('initialXY')[1] + 'px';
176 this._resizeEl.style.left = this.get('initialXY')[0] + 'px';
177 this._resizeMaskEl.style.height = Math.floor(this.get('initHeight')) + 'px';
178 this._resizeMaskEl.style.width = Math.floor(this.get('initWidth')) + 'px';
180 this._resize = new YAHOO.util.Resize(this._resizeEl, {
184 status: this.get('status'),
185 minWidth: this.get('minWidth'),
186 minHeight: this.get('minHeight'),
187 ratio: this.get('ratio'),
188 autoRatio: this.get('autoRatio'),
189 height: this.get('initHeight'),
190 width: this.get('initWidth')
193 this._setBackgroundImage(this.get('element').getAttribute('src', 2));
194 this._setBackgroundPosition(-(this.get('initialXY')[0]), -(this.get('initialXY')[1]));
196 this._resize.on('startResize', this._handleStartResizeEvent, this, true);
197 this._resize.on('endResize', this._handleEndResizeEvent, this, true);
198 this._resize.on('dragEvent', this._handleDragEvent, this, true);
199 this._resize.on('beforeResize', this._handleBeforeResizeEvent, this, true);
200 this._resize.on('resize', this._handleResizeEvent, this, true);
201 this._resize.dd.on('b4StartDragEvent', this._handleB4DragEvent, this, true);
206 * @method _handleMouseOver
207 * @description Handles the mouseover event
209 _handleMouseOver: function(ev) {
210 var evType = 'keydown';
211 if (YAHOO.env.ua.gecko || YAHOO.env.ua.opera) {
216 if (this.get('useKeys')) {
217 Event.on(document, evType, this._handleKeyPress, this, true);
223 * @method _handleMouseOut
224 * @description Handles the mouseout event
226 _handleMouseOut: function(ev) {
227 var evType = 'keydown';
228 if (YAHOO.env.ua.gecko || YAHOO.env.ua.opera) {
231 this._active = false;
232 if (this.get('useKeys')) {
233 Event.removeListener(document, evType, this._handleKeyPress);
240 * @description Moves the resize element based on the arrow keys
242 _moveEl: function(dir, inc) {
244 region = this._setConstraints(),
250 if ((region.bottom - inc) < 0) {
252 this._resizeEl.style.top = (region.top + region.bottom) + 'px';
257 if ((region.top - inc) < 0) {
259 this._resizeEl.style.top = '0px';
264 if ((region.right - inc) < 0) {
266 this._resizeEl.style.left = (region.left + region.right) + 'px';
271 if ((region.left - inc) < 0) {
273 this._resizeEl.style.left = '0px';
279 this._resizeEl.style.left = (parseInt(this._resizeEl.style.left, 10) - l) + 'px';
280 this._resizeEl.style.top = (parseInt(this._resizeEl.style.top, 10) - t) + 'px';
281 this.fireEvent('moveEvent', { target: 'keypress' });
283 this._setConstraints();
285 this._syncBackgroundPosition();
290 * @method _handleKeyPress
291 * @description Handles the keypress event
293 _handleKeyPress: function(ev) {
294 var kc = Event.getCharCode(ev),
296 inc = ((ev.shiftKey) ? this.get('shiftKeyTick') : this.get('keyTick'));
300 this._moveEl('left', inc);
304 this._moveEl('up', inc);
308 this._moveEl('right', inc);
312 this._moveEl('down', inc);
318 Event.preventDefault(ev);
324 * @method _handleB4DragEvent
325 * @description Handles the DragDrop b4DragEvent event
327 _handleB4DragEvent: function() {
328 this._setConstraints();
333 * @method _handleDragEvent
334 * @description Handles the DragDrop DragEvent event
336 _handleDragEvent: function() {
337 this._syncBackgroundPosition();
338 this.fireEvent('dragEvent', arguments);
339 this.fireEvent('moveEvent', { target: 'dragevent' });
344 * @method _handleBeforeResizeEvent
345 * @description Handles the Resize Utilitys beforeResize event
347 _handleBeforeResizeEvent: function(args) {
348 var region = Dom.getRegion(this.get('element')),
349 c = this._resize._cache,
350 ch = this._resize._currentHandle, h = 0, w = 0;
352 if (args.top && (args.top < region.top)) {
353 h = (c.height + c.top) - region.top;
354 Dom.setY(this._resize.getWrapEl(), region.top);
355 this._resize.getWrapEl().style.height = h + 'px';
356 this._resize._cache.height = h;
357 this._resize._cache.top = region.top;
358 this._syncBackgroundPosition();
361 if (args.left && (args.left < region.left)) {
362 w = (c.width + c.left) - region.left;
363 Dom.setX(this._resize.getWrapEl(), region.left);
364 this._resize._cache.left = region.left;
365 this._resize.getWrapEl().style.width = w + 'px';
366 this._resize._cache.width = w;
367 this._syncBackgroundPosition();
370 if (ch != 'tl' && ch != 'l' && ch != 'bl') {
371 if (c.left && args.width && ((c.left + args.width) > region.right)) {
372 w = (region.right - c.left);
373 Dom.setX(this._resize.getWrapEl(), (region.right - w));
374 this._resize.getWrapEl().style.width = w + 'px';
375 this._resize._cache.left = (region.right - w);
376 this._resize._cache.width = w;
377 this._syncBackgroundPosition();
381 if (ch != 't' && ch != 'tr' && ch != 'tl') {
382 if (c.top && args.height && ((c.top + args.height) > region.bottom)) {
383 h = (region.bottom - c.top);
384 Dom.setY(this._resize.getWrapEl(), (region.bottom - h));
385 this._resize.getWrapEl().style.height = h + 'px';
386 this._resize._cache.height = h;
387 this._resize._cache.top = (region.bottom - h);
388 this._syncBackgroundPosition();
395 * @method _handleResizeMaskEl
396 * @description Resizes the inner mask element
398 _handleResizeMaskEl: function() {
399 var a = this._resize._cache;
400 this._resizeMaskEl.style.height = Math.floor(a.height) + 'px';
401 this._resizeMaskEl.style.width = Math.floor(a.width) + 'px';
405 * @method _handleResizeEvent
406 * @param Event ev The Resize Utilitys resize event.
407 * @description Handles the Resize Utilitys Resize event
409 _handleResizeEvent: function(ev) {
410 this._setConstraints(true);
411 this._syncBackgroundPosition();
412 this.fireEvent('resizeEvent', arguments);
413 this.fireEvent('moveEvent', { target: 'resizeevent' });
418 * @method _syncBackgroundPosition
419 * @description Syncs the packground position of the resize element with the resize elements top and left style position
421 _syncBackgroundPosition: function() {
422 this._handleResizeMaskEl();
423 this._setBackgroundPosition(-(parseInt(this._resizeEl.style.left, 10)), -(parseInt(this._resizeEl.style.top, 10)));
428 * @method _setBackgroundPosition
429 * @param Number l The left position
430 * @param Number t The top position
431 * @description Sets the background image position to the top and left position
433 _setBackgroundPosition: function(l, t) {
434 var bl = parseInt(Dom.getStyle(this._resize.get('element'), 'borderLeftWidth'), 10);
435 var bt = parseInt(Dom.getStyle(this._resize.get('element'), 'borderTopWidth'), 10);
442 var mask = this._resize.getWrapEl().firstChild;
443 var pos = (l - bl) + 'px ' + (t - bt) + 'px';
444 this._resizeMaskEl.style.backgroundPosition = pos;
449 * @method _setBackgroundImage
450 * @param String url The url of the image
451 * @description Sets the background image of the resize element
453 _setBackgroundImage: function(url) {
454 var mask = this._resize.getWrapEl().firstChild;
456 mask.style.backgroundImage = 'url(' + url + '#)';
461 * @method _handleEndResizeEvent
462 * @description Handles the Resize Utilitys endResize event
464 _handleEndResizeEvent: function() {
465 this._setConstraints(true);
469 * @method _handleStartResizeEvent
470 * @description Handles the Resize Utilitys startResize event
472 _handleStartResizeEvent: function() {
473 this._setConstraints(true);
475 var h = this._resize._cache.height,
476 w = this._resize._cache.width,
477 t = parseInt(this._resize.getWrapEl().style.top, 10),
478 l = parseInt(this._resize.getWrapEl().style.left, 10),
481 switch (this._resize._currentHandle) {
483 maxH = (h + this._resize.dd.bottomConstraint);
486 maxW = (w + this._resize.dd.leftConstraint);
490 maxW = (w + this._resize.dd.rightConstraint);
493 maxH = (h + this._resize.dd.bottomConstraint);
494 maxW = (w + this._resize.dd.rightConstraint);
498 maxW = (w + this._resize.dd.rightConstraint);
504 //this._resize.set('maxHeight', maxH);
507 //this._resize.set('maxWidth', maxW);
510 this.fireEvent('startResizeEvent', arguments);
515 * @method _setConstraints
516 * @param Boolean inside Used when called from inside a resize event, false by default (dragging)
517 * @description Set the DragDrop constraints to keep the element inside the crop area.
518 * @return {Object} Object containing Top, Right, Bottom and Left constraints
520 _setConstraints: function(inside) {
521 var resize = this._resize;
522 resize.dd.resetConstraints();
523 var height = parseInt(resize.get('height'), 10),
524 width = parseInt(resize.get('width'), 10);
526 //Called from inside the resize callback
527 height = resize._cache.height;
528 width = resize._cache.width;
531 //Get the top, right, bottom and left positions
532 var region = Dom.getRegion(this.get('element'));
533 //Get the element we are working on
534 var el = resize.getWrapEl();
536 //Get the xy position of it
537 var xy = Dom.getXY(el);
539 //Set left to x minus left
540 var left = xy[0] - region.left;
542 //Set right to right minus x minus width
543 var right = region.right - xy[0] - width;
545 //Set top to y minus top
546 var top = xy[1] - region.top;
548 //Set bottom to bottom minus y minus height
549 var bottom = region.bottom - xy[1] - height;
555 resize.dd.setXConstraint(left, right);
556 resize.dd.setYConstraint(top, bottom);
569 * @method getCropCoords
570 * @description Returns the coordinates needed to crop the image
571 * @return {Object} The top, left, height, width and image url of the image being cropped
573 getCropCoords: function() {
575 top: parseInt(this._resize.getWrapEl().style.top, 10),
576 left: parseInt(this._resize.getWrapEl().style.left, 10),
577 height: this._resize._cache.height,
578 width: this._resize._cache.width,
585 * @description Resets the crop element back to it's original position
586 * @return {<a href="YAHOO.widget.ImageCropper.html">YAHOO.widget.ImageCropper</a>} The ImageCropper instance
589 this._resize.resize(null, this.get('initHeight'), this.get('initWidth'), 0, 0, true);
590 this._resizeEl.style.top = this.get('initialXY')[1] + 'px';
591 this._resizeEl.style.left = this.get('initialXY')[0] + 'px';
592 this._syncBackgroundPosition();
598 * @description Get the HTML reference for the image element.
599 * @return {HTMLElement} The image element
602 return this.get('element');
605 * @method getResizeEl
606 * @description Get the HTML reference for the resize element.
607 * @return {HTMLElement} The resize element
609 getResizeEl: function() {
610 return this._resizeEl;
614 * @description Get the HTML reference for the wrap element.
615 * @return {HTMLElement} The wrap element
617 getWrapEl: function() {
623 * @description Get the HTML reference for the mask element.
624 * @return {HTMLElement} The mask element
626 getMaskEl: function() {
631 * @method getResizeMaskEl
632 * @description Get the HTML reference for the resizable object's mask element.
633 * @return {HTMLElement} The resize objects mask element.
635 getResizeMaskEl: function() {
636 return this._resizeMaskEl;
640 * @method getResizeObject
641 * @description Get the Resize Utility object.
642 * @return {<a href="YAHOO.util.Resize.html">YAHOO.util.Resize</a>} The Resize instance
644 getResizeObject: function() {
651 * @description The ImageCropper class's initialization method
653 init: function(p_oElement, p_oAttributes) {
654 Crop.superclass.init.call(this, p_oElement, p_oAttributes);
658 if (!Lang.isString(id)) {
659 if (id.tagName && (id.tagName.toLowerCase() == 'img')) {
660 id = Dom.generateId(id);
665 var el = Dom.get(id);
666 if (el.tagName && el.tagName.toLowerCase() == 'img') {
675 Crop._instances[id] = this;
678 this._createResize();
679 this._setConstraints();
684 * @method initAttributes
685 * @description Initializes all of the configuration attributes used to create a croppable element.
686 * @param {Object} attr Object literal specifying a set of
687 * configuration attributes used to create the widget.
690 initAttributes: function(attr) {
691 Crop.superclass.initAttributes.call(this, attr);
694 * @attribute initialXY
695 * @description Array of the XY position that we need to set the crop element to when we build it. Defaults to [10, 10]
698 this.setAttributeConfig('initialXY', {
699 validator: YAHOO.lang.isArray,
700 value: attr.initialXY || [10, 10]
704 * @description The pixel tick for the arrow keys, defaults to 1
707 this.setAttributeConfig('keyTick', {
708 validator: YAHOO.lang.isNumber,
709 value: attr.keyTick || 1
713 * @attribute shiftKeyTick
714 * @description The pixel tick for shift + the arrow keys, defaults to 10
717 this.setAttributeConfig('shiftKeyTick', {
718 validator: YAHOO.lang.isNumber,
719 value: attr.shiftKeyTick || 10
724 * @description Should we use the Arrow keys to position the crop element, defaults to true
727 this.setAttributeConfig('useKeys', {
728 validator: YAHOO.lang.isBoolean,
729 value: ((attr.useKeys === false) ? false : true)
734 * @description Show the Resize Utility status, defaults to true
737 this.setAttributeConfig('status', {
738 validator: YAHOO.lang.isBoolean,
739 value: ((attr.status === false) ? false : true),
740 method: function(status) {
742 this._resize.set('status', status);
748 * @attribute minHeight
749 * @description MinHeight of the crop area, default 50
752 this.setAttributeConfig('minHeight', {
753 validator: YAHOO.lang.isNumber,
754 value: attr.minHeight || 50,
755 method: function(h) {
757 this._resize.set('minHeight', h);
763 * @attribute minWidth
764 * @description MinWidth of the crop area, default 50.
767 this.setAttributeConfig('minWidth', {
768 validator: YAHOO.lang.isNumber,
769 value: attr.minWidth || 50,
770 method: function(w) {
772 this._resize.set('minWidth', w);
779 * @description Set the ratio config option of the Resize Utlility, default false
782 this.setAttributeConfig('ratio', {
783 validator: YAHOO.lang.isBoolean,
784 value: attr.ratio || false,
785 method: function(r) {
787 this._resize.set('ratio', r);
794 * @description Set the autoRatio config option of the Resize Utlility, default true
797 this.setAttributeConfig('autoRatio', {
798 validator: YAHOO.lang.isBoolean,
799 value: ((attr.autoRatio === false) ? false : true),
800 method: function(a) {
802 this._resize.set('autoRatio', a);
808 * @attribute initHeight
809 * @description Set the initlal height of the crop area, defaults to 1/4 of the image height
812 this.setAttributeConfig('initHeight', {
814 validator: YAHOO.lang.isNumber,
815 value: attr.initHeight || (this.get('element').height / 4)
819 * @attribute initWidth
820 * @description Set the initlal width of the crop area, defaults to 1/4 of the image width
823 this.setAttributeConfig('initWidth', {
824 validator: YAHOO.lang.isNumber,
826 value: attr.initWidth || (this.get('element').width / 4)
832 * @description Destroys the ImageCropper object and all of it's elements & listeners.
834 destroy: function() {
835 this._resize.destroy();
836 this._resizeEl.parentNode.removeChild(this._resizeEl);
837 this._mask.parentNode.removeChild(this._mask);
838 Event.purgeElement(this._wrap);
839 this._wrap.parentNode.replaceChild(this.get('element'), this._wrap);
841 //Brutal Object Destroy
842 for (var i in this) {
843 if (Lang.hasOwnProperty(this, i)) {
851 * @description Returns a string representing the ImageCropper Object.
854 toString: function() {
856 return 'ImageCropper (#' + this.get('id') + ')';
858 return 'Image Cropper';
862 YAHOO.widget.ImageCropper = Crop;
866 * @description Fires when the DragDrop dragEvent
867 * @type YAHOO.util.CustomEvent
870 * @event startResizeEvent
871 * @description Fires when when a resize action is started.
872 * @type YAHOO.util.CustomEvent
876 * @description Fires on every element resize.
877 * @type YAHOO.util.CustomEvent
881 * @description Fires on every element move. Inside these methods: _handleKeyPress, _handleDragEvent, _handleResizeEvent
882 * @type YAHOO.util.CustomEvent
887 YAHOO.register("imagecropper", YAHOO.widget.ImageCropper, {version: "2.9.0", build: "2800"});