2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 * @description <p>Creates a Image Cropper control.</p>
9 * @namespace YAHOO.widget
10 * @requires yahoo, dom, dragdrop, element, event, resize
11 * @module imagecropper
15 var Dom = YAHOO.util.Dom,
16 Event = YAHOO.util.Event,
22 * @description <p>Creates a Image Cropper control.</p>
23 * @extends YAHOO.util.Element
24 * @param {String/HTMLElement} el The image element to make croppable.
25 * @param {Object} attrs Object liternal containing configuration parameters.
27 var Crop = function(el, config) {
28 YAHOO.log('Initializing', 'log', 'ImageCropper');
31 attributes: config || {}
34 Crop.superclass.constructor.call(this, oConfig.element, oConfig.attributes);
40 * @property _instances
41 * @description Internal hash table for all ImageCropper instances
47 * @method getCropperById
48 * @description Get's an ImageCropper object by the HTML id of the image associated with the ImageCropper object.
49 * @return {Object} The ImageCropper Object
51 Crop.getCropperById = function(id) {
52 if (Crop._instances[id]) {
53 return Crop._instances[id];
58 YAHOO.extend(Crop, YAHOO.util.Element, {
62 * @description The CSS class used to wrap the element
69 * @description The CSS class for the mask element
72 CSS_MASK: 'yui-crop-mask',
75 * @property CSS_RESIZE_MASK
76 * @description The CSS class for the mask inside the resize element
79 CSS_RESIZE_MASK: 'yui-crop-resize-mask',
84 * @description The url of the image we are cropping
91 * @description Flag to determine if the crop region is active
98 * @description A reference to the Resize Utility used in this Cropper Instance
104 * @property _resizeEl
105 * @description The HTML Element used to create the Resize Oject
111 * @property _resizeMaskEl
112 * @description The HTML Element used to create the Resize mask
119 * @description The HTML Element created to wrap the image
126 * @description The HTML Element created to "mask" the image being cropped
132 * @method _createWrap
133 * @description Creates the wrapper element used to wrap the image
135 _createWrap: function() {
136 YAHOO.log('Creating the wrap element', 'log', 'ImageCropper');
137 this._wrap = document.createElement('div');
138 this._wrap.id = this.get('element').id + '_wrap';
139 this._wrap.className = this.CSS_MAIN;
140 var el = this.get('element');
141 this._wrap.style.width = el.width ? el.width + 'px' : Dom.getStyle(el, 'width');
142 this._wrap.style.height = el.height ? el.height + 'px' : Dom.getStyle(el, 'height');
144 var par = this.get('element').parentNode;
145 par.replaceChild(this._wrap, this.get('element'));
146 this._wrap.appendChild(this.get('element'));
148 Event.on(this._wrap, 'mouseover', this._handleMouseOver, this, true);
149 Event.on(this._wrap, 'mouseout', this._handleMouseOut, this, true);
151 Event.on(this._wrap, 'click', function(ev) { Event.stopEvent(ev); }, this, true);
156 * @method _createMask
157 * @description Creates the mask element used to mask the image
159 _createMask: function() {
160 YAHOO.log('Creating the Mask', 'log', 'ImageCropper');
161 this._mask = document.createElement('div');
162 this._mask.className = this.CSS_MASK;
163 this._wrap.appendChild(this._mask);
168 * @method _createResize
169 * @description Creates the resize element and the instance of the Resize Utility
171 _createResize: function() {
172 YAHOO.log('Creating the Resize element', 'log', 'ImageCropper');
173 this._resizeEl = document.createElement('div');
174 this._resizeEl.className = YAHOO.util.Resize.prototype.CSS_RESIZE;
175 this._resizeEl.style.position = 'absolute';
177 this._resizeEl.innerHTML = '<div class="' + this.CSS_RESIZE_MASK + '"></div>';
178 this._resizeMaskEl = this._resizeEl.firstChild;
179 this._wrap.appendChild(this._resizeEl);
180 this._resizeEl.style.top = this.get('initialXY')[1] + 'px';
181 this._resizeEl.style.left = this.get('initialXY')[0] + 'px';
182 this._resizeMaskEl.style.height = Math.floor(this.get('initHeight')) + 'px';
183 this._resizeMaskEl.style.width = Math.floor(this.get('initWidth')) + 'px';
185 this._resize = new YAHOO.util.Resize(this._resizeEl, {
189 status: this.get('status'),
190 minWidth: this.get('minWidth'),
191 minHeight: this.get('minHeight'),
192 ratio: this.get('ratio'),
193 autoRatio: this.get('autoRatio'),
194 height: this.get('initHeight'),
195 width: this.get('initWidth')
198 this._setBackgroundImage(this.get('element').getAttribute('src', 2));
199 this._setBackgroundPosition(-(this.get('initialXY')[0]), -(this.get('initialXY')[1]));
201 this._resize.on('startResize', this._handleStartResizeEvent, this, true);
202 this._resize.on('endResize', this._handleEndResizeEvent, this, true);
203 this._resize.on('dragEvent', this._handleDragEvent, this, true);
204 this._resize.on('beforeResize', this._handleBeforeResizeEvent, this, true);
205 this._resize.on('resize', this._handleResizeEvent, this, true);
206 this._resize.dd.on('b4StartDragEvent', this._handleB4DragEvent, this, true);
211 * @method _handleMouseOver
212 * @description Handles the mouseover event
214 _handleMouseOver: function(ev) {
215 var evType = 'keydown';
216 if (YAHOO.env.ua.gecko || YAHOO.env.ua.opera) {
221 if (this.get('useKeys')) {
222 Event.on(document, evType, this._handleKeyPress, this, true);
228 * @method _handleMouseOut
229 * @description Handles the mouseout event
231 _handleMouseOut: function(ev) {
232 var evType = 'keydown';
233 if (YAHOO.env.ua.gecko || YAHOO.env.ua.opera) {
236 this._active = false;
237 if (this.get('useKeys')) {
238 Event.removeListener(document, evType, this._handleKeyPress);
245 * @description Moves the resize element based on the arrow keys
247 _moveEl: function(dir, inc) {
248 YAHOO.log('Moving the element', 'log', 'ImageCropper');
250 region = this._setConstraints(),
256 if ((region.bottom - inc) < 0) {
258 this._resizeEl.style.top = (region.top + region.bottom) + 'px';
263 if ((region.top - inc) < 0) {
265 this._resizeEl.style.top = '0px';
270 if ((region.right - inc) < 0) {
272 this._resizeEl.style.left = (region.left + region.right) + 'px';
277 if ((region.left - inc) < 0) {
279 this._resizeEl.style.left = '0px';
285 YAHOO.log('Moving via Key Listener: ' + dir, 'log', 'ImageCropper');
286 this._resizeEl.style.left = (parseInt(this._resizeEl.style.left, 10) - l) + 'px';
287 this._resizeEl.style.top = (parseInt(this._resizeEl.style.top, 10) - t) + 'px';
288 this.fireEvent('moveEvent', { target: 'keypress' });
290 this._setConstraints();
292 this._syncBackgroundPosition();
297 * @method _handleKeyPress
298 * @description Handles the keypress event
300 _handleKeyPress: function(ev) {
301 var kc = Event.getCharCode(ev),
303 inc = ((ev.shiftKey) ? this.get('shiftKeyTick') : this.get('keyTick'));
307 this._moveEl('left', inc);
311 this._moveEl('up', inc);
315 this._moveEl('right', inc);
319 this._moveEl('down', inc);
325 Event.preventDefault(ev);
331 * @method _handleB4DragEvent
332 * @description Handles the DragDrop b4DragEvent event
334 _handleB4DragEvent: function() {
335 this._setConstraints();
340 * @method _handleDragEvent
341 * @description Handles the DragDrop DragEvent event
343 _handleDragEvent: function() {
344 this._syncBackgroundPosition();
345 this.fireEvent('dragEvent', arguments);
346 this.fireEvent('moveEvent', { target: 'dragevent' });
351 * @method _handleBeforeResizeEvent
352 * @description Handles the Resize Utilitys beforeResize event
354 _handleBeforeResizeEvent: function(args) {
355 var region = Dom.getRegion(this.get('element')),
356 c = this._resize._cache,
357 ch = this._resize._currentHandle, h = 0, w = 0;
359 if (args.top && (args.top < region.top)) {
360 h = (c.height + c.top) - region.top;
361 Dom.setY(this._resize.getWrapEl(), region.top);
362 this._resize.getWrapEl().style.height = h + 'px';
363 this._resize._cache.height = h;
364 this._resize._cache.top = region.top;
365 this._syncBackgroundPosition();
368 if (args.left && (args.left < region.left)) {
369 w = (c.width + c.left) - region.left;
370 Dom.setX(this._resize.getWrapEl(), region.left);
371 this._resize._cache.left = region.left;
372 this._resize.getWrapEl().style.width = w + 'px';
373 this._resize._cache.width = w;
374 this._syncBackgroundPosition();
377 if (ch != 'tl' && ch != 'l' && ch != 'bl') {
378 if (c.left && args.width && ((c.left + args.width) > region.right)) {
379 w = (region.right - c.left);
380 Dom.setX(this._resize.getWrapEl(), (region.right - w));
381 this._resize.getWrapEl().style.width = w + 'px';
382 this._resize._cache.left = (region.right - w);
383 this._resize._cache.width = w;
384 this._syncBackgroundPosition();
388 if (ch != 't' && ch != 'tr' && ch != 'tl') {
389 if (c.top && args.height && ((c.top + args.height) > region.bottom)) {
390 h = (region.bottom - c.top);
391 Dom.setY(this._resize.getWrapEl(), (region.bottom - h));
392 this._resize.getWrapEl().style.height = h + 'px';
393 this._resize._cache.height = h;
394 this._resize._cache.top = (region.bottom - h);
395 this._syncBackgroundPosition();
402 * @method _handleResizeMaskEl
403 * @description Resizes the inner mask element
405 _handleResizeMaskEl: function() {
406 var a = this._resize._cache;
407 this._resizeMaskEl.style.height = Math.floor(a.height) + 'px';
408 this._resizeMaskEl.style.width = Math.floor(a.width) + 'px';
412 * @method _handleResizeEvent
413 * @param Event ev The Resize Utilitys resize event.
414 * @description Handles the Resize Utilitys Resize event
416 _handleResizeEvent: function(ev) {
417 this._setConstraints(true);
418 this._syncBackgroundPosition();
419 this.fireEvent('resizeEvent', arguments);
420 this.fireEvent('moveEvent', { target: 'resizeevent' });
425 * @method _syncBackgroundPosition
426 * @description Syncs the packground position of the resize element with the resize elements top and left style position
428 _syncBackgroundPosition: function() {
429 this._handleResizeMaskEl();
430 this._setBackgroundPosition(-(parseInt(this._resizeEl.style.left, 10)), -(parseInt(this._resizeEl.style.top, 10)));
435 * @method _setBackgroundPosition
436 * @param Number l The left position
437 * @param Number t The top position
438 * @description Sets the background image position to the top and left position
440 _setBackgroundPosition: function(l, t) {
441 //YAHOO.log('Setting the image background position of the mask to: (' + l + ', ' + t + ')', 'log', 'ImageCropper');
442 var bl = parseInt(Dom.getStyle(this._resize.get('element'), 'borderLeftWidth'), 10);
443 var bt = parseInt(Dom.getStyle(this._resize.get('element'), 'borderTopWidth'), 10);
450 var mask = this._resize.getWrapEl().firstChild;
451 var pos = (l - bl) + 'px ' + (t - bt) + 'px';
452 this._resizeMaskEl.style.backgroundPosition = pos;
457 * @method _setBackgroundImage
458 * @param String url The url of the image
459 * @description Sets the background image of the resize element
461 _setBackgroundImage: function(url) {
462 YAHOO.log('Setting the background image', 'log', 'ImageCropper');
463 var mask = this._resize.getWrapEl().firstChild;
465 mask.style.backgroundImage = 'url(' + url + '#)';
470 * @method _handleEndResizeEvent
471 * @description Handles the Resize Utilitys endResize event
473 _handleEndResizeEvent: function() {
474 this._setConstraints(true);
478 * @method _handleStartResizeEvent
479 * @description Handles the Resize Utilitys startResize event
481 _handleStartResizeEvent: function() {
482 this._setConstraints(true);
484 var h = this._resize._cache.height,
485 w = this._resize._cache.width,
486 t = parseInt(this._resize.getWrapEl().style.top, 10),
487 l = parseInt(this._resize.getWrapEl().style.left, 10),
490 switch (this._resize._currentHandle) {
492 maxH = (h + this._resize.dd.bottomConstraint);
495 maxW = (w + this._resize.dd.leftConstraint);
499 maxW = (w + this._resize.dd.rightConstraint);
502 maxH = (h + this._resize.dd.bottomConstraint);
503 maxW = (w + this._resize.dd.rightConstraint);
507 maxW = (w + this._resize.dd.rightConstraint);
513 YAHOO.log('Setting the maxHeight on the resize object to: ' + maxH, 'log', 'ImageCropper');
514 //this._resize.set('maxHeight', maxH);
517 YAHOO.log('Setting the maxWidth on the resize object to: ' + maxW, 'log', 'ImageCropper');
518 //this._resize.set('maxWidth', maxW);
521 this.fireEvent('startResizeEvent', arguments);
526 * @method _setConstraints
527 * @param Boolean inside Used when called from inside a resize event, false by default (dragging)
528 * @description Set the DragDrop constraints to keep the element inside the crop area.
529 * @return {Object} Object containing Top, Right, Bottom and Left constraints
531 _setConstraints: function(inside) {
532 YAHOO.log('Setting Contraints', 'log', 'ImageCropper');
533 var resize = this._resize;
534 resize.dd.resetConstraints();
535 var height = parseInt(resize.get('height'), 10),
536 width = parseInt(resize.get('width'), 10);
538 //Called from inside the resize callback
539 height = resize._cache.height;
540 width = resize._cache.width;
543 //Get the top, right, bottom and left positions
544 var region = Dom.getRegion(this.get('element'));
545 //Get the element we are working on
546 var el = resize.getWrapEl();
548 //Get the xy position of it
549 var xy = Dom.getXY(el);
551 //Set left to x minus left
552 var left = xy[0] - region.left;
554 //Set right to right minus x minus width
555 var right = region.right - xy[0] - width;
557 //Set top to y minus top
558 var top = xy[1] - region.top;
560 //Set bottom to bottom minus y minus height
561 var bottom = region.bottom - xy[1] - height;
567 resize.dd.setXConstraint(left, right);
568 resize.dd.setYConstraint(top, bottom);
569 YAHOO.log('Constraints: ' + top + ',' + right + ',' + bottom + ',' + left, 'log', 'ImageCropper');
582 * @method getCropCoords
583 * @description Returns the coordinates needed to crop the image
584 * @return {Object} The top, left, height, width and image url of the image being cropped
586 getCropCoords: function() {
588 top: parseInt(this._resize.getWrapEl().style.top, 10),
589 left: parseInt(this._resize.getWrapEl().style.left, 10),
590 height: this._resize._cache.height,
591 width: this._resize._cache.width,
594 YAHOO.log('Getting the crop coordinates: ' + Lang.dump(coords), 'log', 'ImageCropper');
599 * @description Resets the crop element back to it's original position
600 * @return {<a href="YAHOO.widget.ImageCropper.html">YAHOO.widget.ImageCropper</a>} The ImageCropper instance
603 YAHOO.log('Resetting the control', 'log', 'ImageCropper');
604 this._resize.resize(null, this.get('initHeight'), this.get('initWidth'), 0, 0, true);
605 this._resizeEl.style.top = this.get('initialXY')[1] + 'px';
606 this._resizeEl.style.left = this.get('initialXY')[0] + 'px';
607 this._syncBackgroundPosition();
613 * @description Get the HTML reference for the image element.
614 * @return {HTMLElement} The image element
617 return this.get('element');
620 * @method getResizeEl
621 * @description Get the HTML reference for the resize element.
622 * @return {HTMLElement} The resize element
624 getResizeEl: function() {
625 return this._resizeEl;
629 * @description Get the HTML reference for the wrap element.
630 * @return {HTMLElement} The wrap element
632 getWrapEl: function() {
638 * @description Get the HTML reference for the mask element.
639 * @return {HTMLElement} The mask element
641 getMaskEl: function() {
646 * @method getResizeMaskEl
647 * @description Get the HTML reference for the resizable object's mask element.
648 * @return {HTMLElement} The resize objects mask element.
650 getResizeMaskEl: function() {
651 return this._resizeMaskEl;
655 * @method getResizeObject
656 * @description Get the Resize Utility object.
657 * @return {<a href="YAHOO.util.Resize.html">YAHOO.util.Resize</a>} The Resize instance
659 getResizeObject: function() {
666 * @description The ImageCropper class's initialization method
668 init: function(p_oElement, p_oAttributes) {
669 YAHOO.log('init', 'info', 'ImageCropper');
670 Crop.superclass.init.call(this, p_oElement, p_oAttributes);
674 if (!Lang.isString(id)) {
675 if (id.tagName && (id.tagName.toLowerCase() == 'img')) {
676 id = Dom.generateId(id);
678 YAHOO.log('Element is not an image.', 'error', 'ImageCropper');
682 var el = Dom.get(id);
683 if (el.tagName && el.tagName.toLowerCase() == 'img') {
686 YAHOO.log('Element is not an image.', 'error', 'ImageCropper');
693 Crop._instances[id] = this;
696 this._createResize();
697 this._setConstraints();
702 * @method initAttributes
703 * @description Initializes all of the configuration attributes used to create a croppable element.
704 * @param {Object} attr Object literal specifying a set of
705 * configuration attributes used to create the widget.
708 initAttributes: function(attr) {
709 Crop.superclass.initAttributes.call(this, attr);
712 * @attribute initialXY
713 * @description Array of the XY position that we need to set the crop element to when we build it. Defaults to [10, 10]
716 this.setAttributeConfig('initialXY', {
718 validator: YAHOO.lang.isArray,
719 value: attr.initialXY || [10, 10]
723 * @description The pixel tick for the arrow keys, defaults to 1
726 this.setAttributeConfig('keyTick', {
727 validator: YAHOO.lang.isNumber,
728 value: attr.keyTick || 1
732 * @attribute shiftKeyTick
733 * @description The pixel tick for shift + the arrow keys, defaults to 10
736 this.setAttributeConfig('shiftKeyTick', {
737 validator: YAHOO.lang.isNumber,
738 value: attr.shiftKeyTick || 10
743 * @description Should we use the Arrow keys to position the crop element, defaults to true
746 this.setAttributeConfig('useKeys', {
747 validator: YAHOO.lang.isBoolean,
748 value: ((attr.useKeys === false) ? false : true)
753 * @description Show the Resize Utility status, defaults to true
756 this.setAttributeConfig('status', {
757 validator: YAHOO.lang.isBoolean,
758 value: ((attr.status === false) ? false : true),
759 method: function(status) {
761 this._resize.set('status', status);
767 * @attribute minHeight
768 * @description MinHeight of the crop area, default 50
771 this.setAttributeConfig('minHeight', {
772 validator: YAHOO.lang.isNumber,
773 value: attr.minHeight || 50,
774 method: function(h) {
776 this._resize.set('minHeight', h);
782 * @attribute minWidth
783 * @description MinWidth of the crop area, default 50.
786 this.setAttributeConfig('minWidth', {
787 validator: YAHOO.lang.isNumber,
788 value: attr.minWidth || 50,
789 method: function(w) {
791 this._resize.set('minWidth', w);
798 * @description Set the ratio config option of the Resize Utlility, default false
801 this.setAttributeConfig('ratio', {
802 validator: YAHOO.lang.isBoolean,
803 value: attr.ratio || false,
804 method: function(r) {
806 this._resize.set('ratio', r);
813 * @description Set the autoRatio config option of the Resize Utlility, default true
816 this.setAttributeConfig('autoRatio', {
817 validator: YAHOO.lang.isBoolean,
818 value: ((attr.autoRatio === false) ? false : true),
819 method: function(a) {
821 this._resize.set('autoRatio', a);
827 * @attribute initHeight
828 * @description Set the initlal height of the crop area, defaults to 1/4 of the image height
831 this.setAttributeConfig('initHeight', {
833 validator: YAHOO.lang.isNumber,
834 value: attr.initHeight || (this.get('element').height / 4)
838 * @attribute initWidth
839 * @description Set the initlal width of the crop area, defaults to 1/4 of the image width
842 this.setAttributeConfig('initWidth', {
843 validator: YAHOO.lang.isNumber,
845 value: attr.initWidth || (this.get('element').width / 4)
851 * @description Destroys the ImageCropper object and all of it's elements & listeners.
853 destroy: function() {
854 YAHOO.log('Destroying the ImageCropper', 'info', 'ImageCropper');
855 this._resize.destroy();
856 this._resizeEl.parentNode.removeChild(this._resizeEl);
857 this._mask.parentNode.removeChild(this._mask);
858 Event.purgeElement(this._wrap);
859 this._wrap.parentNode.replaceChild(this.get('element'), this._wrap);
861 //Brutal Object Destroy
862 for (var i in this) {
863 if (Lang.hasOwnProperty(this, i)) {
871 * @description Returns a string representing the ImageCropper Object.
874 toString: function() {
876 return 'ImageCropper (#' + this.get('id') + ')';
878 return 'Image Cropper';
882 YAHOO.widget.ImageCropper = Crop;
886 * @description Fires when the DragDrop dragEvent
887 * @type YAHOO.util.CustomEvent
890 * @event startResizeEvent
891 * @description Fires when when a resize action is started.
892 * @type YAHOO.util.CustomEvent
896 * @description Fires on every element resize.
897 * @type YAHOO.util.CustomEvent
901 * @description Fires on every element move. Inside these methods: _handleKeyPress, _handleDragEvent, _handleResizeEvent
902 * @type YAHOO.util.CustomEvent
907 YAHOO.register("imagecropper", YAHOO.widget.ImageCropper, {version: "2.8.0r4", build: "2449"});