/* * iviewer widget for jquery ui * https://github.com/can3p/iviewer * * copyright (c) 2009 - 2013 dmitry petrov * dual licensed under the mit license. * - http://www.opensource.org/licenses/mit-license.php * * author: dmitry petrov * version: 0.7.11 */ ( function( $, undefined ) { //this code was taken from the https://github.com/furf/jquery-ui-touch-punch var mouseevents = { touchstart: 'mousedown', touchmove: 'mousemove', touchend: 'mouseup' }, gesturessupport = 'ongesturestart' in document.createelement('div'); /** * convert a touch event to a mouse-like */ function makemouseevent (event) { var touch = event.originalevent.changedtouches[0]; return $.extend(event, { type: mouseevents[event.type], which: 1, pagex: touch.pagex, pagey: touch.pagey, screenx: touch.screenx, screeny: touch.screeny, clientx: touch.clientx, clienty: touch.clienty, istouchevent: true }); } var mouseproto = $.ui.mouse.prototype, _mouseinit = $.ui.mouse.prototype._mouseinit; mouseproto._mouseinit = function() { var self = this; self._touchactive = false; this.element.bind( 'touchstart.' + this.widgetname, function(event) { if (gesturessupport && event.originalevent.touches.length > 1) { return; } self._touchactive = true; return self._mousedown(makemouseevent(event)); }); // these delegates are required to keep context this._mousemovedelegate = function(event) { if (gesturessupport && event.originalevent.touches && event.originalevent.touches.length > 1) { return; } if (self._touchactive) { return self._mousemove(makemouseevent(event)); } }; this._mouseupdelegate = function(event) { if (self._touchactive) { self._touchactive = false; return self._mouseup(makemouseevent(event)); } }; $(document) .bind('touchmove.'+ this.widgetname, this._mousemovedelegate) .bind('touchend.' + this.widgetname, this._mouseupdelegate); _mouseinit.apply(this); }; /** * simple implementation of jquery like getters/setters * var val = something(); * something(val); */ var setter = function(setter, getter) { return function(val) { if (arguments.length === 0) { return getter.apply(this); } else { setter.apply(this, arguments); } } }; /** * internet explorer rotates image relative left top corner, so we should * shift image when it's rotated. */ var ietransforms = { '0': { marginleft: 0, margintop: 0, filter: 'progid:dximagetransform.microsoft.matrix(m11=1, m12=0, m21=0, m22=1, sizingmethod="auto expand")' }, '90': { marginleft: -1, margintop: 1, filter: 'progid:dximagetransform.microsoft.matrix(m11=0, m12=-1, m21=1, m22=0, sizingmethod="auto expand")' }, '180': { marginleft: 0, margintop: 0, filter: 'progid:dximagetransform.microsoft.matrix(m11=-1, m12=0, m21=0, m22=-1, sizingmethod="auto expand")' }, '270': { marginleft: -1, margintop: 1, filter: 'progid:dximagetransform.microsoft.matrix(m11=0, m12=1, m21=-1, m22=0, sizingmethod="auto expand")' } }, // this test is the inversion of the css filters test from the modernizr project useietransforms = function() { var modelem = document.createelement('modernizr'), mstyle = modelem.style, omprefixes = 'webkit moz o ms', domprefixes = omprefixes.tolowercase().split(' '), props = ("transform" + ' ' + domprefixes.join("transform ") + "transform").split(' '); /*using 'for' loop instead of 'for in' to avoid issues in ie8*/ for ( var i=0; i< props.length;i++ ) { var prop = props[i]; if ( prop.indexof("-") == -1 && mstyle[prop] !== undefined ) { return false; } } return true; }(); $.widget( "ui.iviewer", $.ui.mouse, { widgeteventprefix: "iviewer", options : { /** * start zoom value for image, not used now * may be equal to "fit" to fit image into container or scale in % **/ zoom: "fit", /** * base value to scale image **/ zoom_base: 100, /** * maximum zoom **/ zoom_max: 800, /** * minimum zoom **/ zoom_min: 14, /** * base of rate multiplier. * zoom is calculated by formula: zoom_base * zoom_delta^rate **/ zoom_delta: 1.4, /** * whether the zoom should be animated. */ zoom_animation: true, /** * if true plugin doesn't add its own controls **/ ui_disabled: false, /** * if false mousewheel will be disabled */ mousewheel: true, /** * if false, plugin doesn't bind resize event on window and this must * be handled manually **/ update_on_resize: true, /** * whether to provide zoom on doubleclick functionality */ zoom_on_dblclick: true, /** * if true the image will fill the container and the image will be distorted */ fill_container: false, /** * event is triggered when zoom value is changed * @param int new zoom value * @return boolean if false zoom action is aborted **/ onzoom: jquery.noop, /** * event is triggered when zoom value is changed after image is set to the new dimensions * @param int new zoom value * @return boolean if false zoom action is aborted **/ onafterzoom: jquery.noop, /** * event is fired on drag begin * @param object coords mouse coordinates on the image * @return boolean if false is returned, drag action is aborted **/ onstartdrag: jquery.noop, /** * event is fired on drag action * @param object coords mouse coordinates on the image **/ ondrag: jquery.noop, /** * event is fired on drag stop * @param object coords mouse coordinates on the image **/ onstopdrag: jquery.noop, /** * event is fired when mouse moves over image * @param object coords mouse coordinates on the image **/ onmousemove: jquery.noop, /** * mouse click event * @param object coords mouse coordinates on the image **/ onclick: jquery.noop, /** * mouse double click event. if used will delay each click event. * if double click event was fired, clicks will not. * * @param object coords mouse coordinates on the image **/ ondblclick: null, /** * event is fired when image starts to load */ onstartload: null, /** * event is fired, when image is loaded and initially positioned */ onfinishload: null, /** * event is fired when image load error occurs */ onerrorload: null }, _create: function() { var me = this; //drag variables this.dx = 0; this.dy = 0; /* object containing actual information about image * @img_object.object - jquery img object * @img_object.orig_{width|height} - original dimensions * @img_object.display_{width|height} - actual dimensions */ this.img_object = {}; this.zoom_object = {}; //object to show zoom status this._angle = 0; this.current_zoom = this.options.zoom; if(this.options.src === null){ return; } this.container = this.element; this._updatecontainerinfo(); //init container this.container.css("overflow","hidden"); if (this.options.update_on_resize == true) { $(window).resize(function() { me.update(); }); } this.img_object = new $.ui.iviewer.imageobject(this.options.zoom_animation); if (this.options.mousewheel) { this.activatemousewheel(this.options.mousewheel); } //bind doubleclick only if callback is not falsy var usedblclick = !!this.options.ondblclick || this.options.zoom_on_dblclick, dblclicktimer = null, clicksnumber = 0; //init object this.img_object.object() .prependto(this.container); //all these tricks are needed to fire either click //or doubleclick events at the same time if (usedblclick) { this.img_object.object() //bind mouse events .click(function(e){ clicksnumber++; cleartimeout(dblclicktimer); dblclicktimer = settimeout(function() { clicksnumber = 0; me._click(e); }, 300); }) .dblclick(function(e){ if (clicksnumber !== 2) return; cleartimeout(dblclicktimer); clicksnumber = 0; me._dblclick(e); }); } else { this.img_object.object() .click(function(e){ me._click(e); }); } this.container.bind('mousemove.iviewer', function(ev) { me._handlemousemove(ev); }); this.loadimage(this.options.src); if(!this.options.ui_disabled) { this.createui(); } this.controls = this.container.find('.iviewer_common') || {}; this._mouseinit(); }, destroy: function() { $.widget.prototype.destroy.call( this ); this._mousedestroy(); this.img_object.object().remove(); /*removing the controls on destroy*/ this.controls.remove(); this.container.off('.iviewer'); this.container.css('overflow', ''); //cleanup styles on destroy }, _updatecontainerinfo: function() { this.options.height = this.container.height(); this.options.width = this.container.width(); }, /** * add or remove the mousewheel effect on the viewer * @param {boolean} isactive * sample : $('#viewer').iviewer('activatemousewheel', true); */ activatemousewheel: function(isactive){ // remove all the previous event bind on the mousewheel this.container.unbind('mousewheel.iviewer'); if (gesturessupport) { this.img_object.object().unbind('touchstart').unbind('gesturechange.iviewer').unbind('gestureend.iviewer'); } if (isactive) { var me = this; this.container.bind('mousewheel.iviewer', function(ev, delta) { //this event is there instead of containing div, because //at opera it triggers many times on div var zoom = (delta > 0)?1:-1, container_offset = me.container.offset(), mouse_pos = { //jquery.mousewheel 3.1.0 uses strange mozmousepixelscroll event //which is not being fixed by jquery.event x: (ev.pagex || ev.originalevent.pagex) - container_offset.left, y: (ev.pagey || ev.originalevent.pagex) - container_offset.top }; me.zoom_by(zoom, mouse_pos); return false; }); if (gesturessupport) { var gesturethrottle = +new date(); var originalscale, originalcenter; this.img_object.object() .bind('touchstart', function(ev) { originalscale = me.current_zoom; var touches = ev.originalevent.touches, container_offset; if (touches.length == 2) { container_offset = me.container.offset(); originalcenter = { x: (touches[0].pagex + touches[1].pagex) / 2 - container_offset.left, y: (touches[0].pagey + touches[1].pagey) / 2 - container_offset.top }; } else { originalcenter = null; } }).bind('gesturechange.iviewer', function(ev) { //do not want to import throttle function from underscore var d = +new date(); if ((d - gesturethrottle) < 50) { return; } gesturethrottle = d; var zoom = originalscale * ev.originalevent.scale; me.set_zoom(zoom, originalcenter); ev.preventdefault(); }).bind('gestureend.iviewer', function(ev) { originalcenter = null; }); } } }, update: function() { this._updatecontainerinfo(); this.setcoords(this.img_object.x(), this.img_object.y()); }, loadimage: function( src ) { this.current_zoom = this.options.zoom; var me = this; this._trigger('onstartload', 0, src); this.container.addclass("iviewer_loading"); this.img_object.load(src, function() { me._fill_orig_dimensions = { width: me.img_object.orig_width(), height: me.img_object.orig_height() }; me._imageloaded(src); }, function() { me._trigger("onerrorload", 0, src); }); }, _imageloaded: function(src) { this.container.removeclass("iviewer_loading"); this.container.addclass("iviewer_cursor"); if(this.options.zoom == "fit"){ this.fit(true); } else { this.set_zoom(this.options.zoom, true); } this._trigger('onfinishload', 0, src); if(this.options.fill_container) { this.fill_container(true); } }, /** * fits image in the container * * @param {boolean} skip_animation **/ fit: function(skip_animation) { var aspect_ratio = this.img_object.orig_width() / this.img_object.orig_height(); var window_ratio = this.options.width / this.options.height; var choose_left = (aspect_ratio > window_ratio); var new_zoom = 0; if(choose_left){ new_zoom = this.options.width / this.img_object.orig_width() * 100; } else { new_zoom = this.options.height / this.img_object.orig_height() * 100; } this.set_zoom(new_zoom, skip_animation); }, /** * center image in container **/ center: function() { this.setcoords(-math.round((this.img_object.display_width() - this.options.width)/2), -math.round((this.img_object.display_height() - this.options.height)/2)); }, /** * move a point in container to the center of display area * @param x a point in container * @param y a point in container **/ moveto: function(x, y) { var dx = x-math.round(this.options.width/2); var dy = y-math.round(this.options.height/2); var new_x = this.img_object.x() - dx; var new_y = this.img_object.y() - dy; this.setcoords(new_x, new_y); }, /** * get container offset object. */ getcontaineroffset: function() { return jquery.extend({}, this.container.offset()); }, /** * set coordinates of upper left corner of image object **/ setcoords: function(x,y) { //do nothing while image is being loaded if(!this.img_object.loaded()) { return; } var coords = this._correctcoords(x,y); this.img_object.x(coords.x); this.img_object.y(coords.y); }, _correctcoords: function( x, y ) { x = parseint(x, 10); y = parseint(y, 10); //check new coordinates to be correct (to be in rect) if(y > 0){ y = 0; } if(x > 0){ x = 0; } if(y + this.img_object.display_height() < this.options.height){ y = this.options.height - this.img_object.display_height(); } if(x + this.img_object.display_width() < this.options.width){ x = this.options.width - this.img_object.display_width(); } if(this.img_object.display_width() <= this.options.width){ x = -(this.img_object.display_width() - this.options.width)/2; } if(this.img_object.display_height() <= this.options.height){ y = -(this.img_object.display_height() - this.options.height)/2; } return { x: x, y:y }; }, /** * convert coordinates on the container to the coordinates on the image (in original size) * * @return object with fields x,y according to coordinates or false * if initial coords are not inside image **/ containertoimage : function (x,y) { var coords = { x : x - this.img_object.x(), y : y - this.img_object.y() }; coords = this.img_object.tooriginalcoords(coords); return { x : util.descalevalue(coords.x, this.current_zoom), y : util.descalevalue(coords.y, this.current_zoom) }; }, /** * convert coordinates on the image (in original size, and zero angle) to the coordinates on the container * * @return object with fields x,y according to coordinates **/ imagetocontainer : function (x,y) { var coords = { x : util.scalevalue(x, this.current_zoom), y : util.scalevalue(y, this.current_zoom) }; return this.img_object.torealcoords(coords); }, /** * get mouse coordinates on the image * @param e - object containing pagex and pagey fields, e.g. mouse event object * * @return object with fields x,y according to coordinates or false * if initial coords are not inside image **/ _getmousecoords : function(e) { var containeroffset = this.container.offset(), coords = this.containertoimage(e.pagex - containeroffset.left, e.pagey - containeroffset.top); return coords; }, /** * fills container entirely by distorting image * * @param {boolean} fill wether to fill the container entirely or not. **/ fill_container: function(fill) { this.options.fill_container = fill; if(fill) { var ratio = this.options.width / this.options.height; if (ratio > 1) this.img_object.orig_width(this.img_object.orig_height() * ratio); else this.img_object.orig_height(this.img_object.orig_width() * ratio); } else { this.img_object.orig_width(this._fill_orig_dimensions.width); this.img_object.orig_height(this._fill_orig_dimensions.height); } this.set_zoom(this.current_zoom); }, /** * set image scale to the new_zoom * * @param {number} new_zoom image scale in % * @param {boolean} skip_animation * @param {x: number, y: number} coordinates of point the should not be moved on zoom. the default is the center of image. **/ set_zoom: function(new_zoom, skip_animation, zoom_center) { if (this._trigger('onzoom', 0, new_zoom) == false) { return; } //do nothing while image is being loaded if(!this.img_object.loaded()) { return; } zoom_center = zoom_center || { x: math.round(this.options.width/2), y: math.round(this.options.height/2) }; if(new_zoom < this.options.zoom_min) { new_zoom = this.options.zoom_min; } else if(new_zoom > this.options.zoom_max) { new_zoom = this.options.zoom_max; } /* we fake these values to make fit zoom properly work */ var old_x, old_y; if(this.current_zoom == "fit") { old_x = zoom_center.x + math.round(this.img_object.orig_width()/2); old_y = zoom_center.y + math.round(this.img_object.orig_height()/2); this.current_zoom = 100; } else { old_x = -this.img_object.x() + zoom_center.x; old_y = -this.img_object.y() + zoom_center.y; } var new_width = util.scalevalue(this.img_object.orig_width(), new_zoom); var new_height = util.scalevalue(this.img_object.orig_height(), new_zoom); var new_x = util.scalevalue( util.descalevalue(old_x, this.current_zoom), new_zoom); var new_y = util.scalevalue( util.descalevalue(old_y, this.current_zoom), new_zoom); new_x = zoom_center.x - new_x; new_y = zoom_center.y - new_y; new_width = math.floor(new_width); new_height = math.floor(new_height); new_x = math.floor(new_x); new_y = math.floor(new_y); this.img_object.display_width(new_width); this.img_object.display_height(new_height); var coords = this._correctcoords( new_x, new_y ), self = this; this.img_object.setimageprops(new_width, new_height, coords.x, coords.y, skip_animation, function() { self._trigger('onafterzoom', 0, new_zoom ); }); this.current_zoom = new_zoom; this.update_status(); }, /** * shows or hides the controls * controls are shown/hidden based on user input * @param boolean flag that specifies whether to show or hide the controls **/ showcontrols: function(flag) { if(flag) { this.controls.fadein(); } else { this.controls.fadeout(); } }, /** * changes zoom scale by delta * zoom is calculated by formula: zoom_base * zoom_delta^rate * @param integer delta number to add to the current multiplier rate number * @param {x: number, y: number=} coordinates of point the should not be moved on zoom. **/ zoom_by: function(delta, zoom_center) { var closest_rate = this.find_closest_zoom_rate(this.current_zoom); var next_rate = closest_rate + delta; var next_zoom = this.options.zoom_base * math.pow(this.options.zoom_delta, next_rate); if(delta > 0 && next_zoom < this.current_zoom) { next_zoom *= this.options.zoom_delta; } if(delta < 0 && next_zoom > this.current_zoom) { next_zoom /= this.options.zoom_delta; } this.set_zoom(next_zoom, undefined, zoom_center); }, /** * rotate image * @param {num} deg degrees amount to rotate. positive values rotate image clockwise. * currently 0, 90, 180, 270 and -90, -180, -270 values are supported * * @param {boolean} abs if the flag is true if, the deg parameter will be considered as * a absolute value and relative otherwise. * @return {num|null} method will return current image angle if called without any arguments. **/ angle: function(deg, abs) { if (arguments.length === 0) { return this.img_object.angle(); } if (deg < -270 || deg > 270 || deg % 90 !== 0) { return; } if (!abs) { deg += this.img_object.angle(); } if (deg < 0) { deg += 360; } if (deg >= 360) { deg -= 360; } if (deg === this.img_object.angle()) { return; } this.img_object.angle(deg); //the rotate behavior is different in all editors. for now we just center the //image. however, it will be better to try to keep the position. this.center(); this._trigger('angle', 0, { angle: this.img_object.angle() }); }, /** * finds closest multiplier rate for value * basing on zoom_base and zoom_delta values from settings * @param number value zoom value to examine **/ find_closest_zoom_rate: function(value) { if(value == this.options.zoom_base) { return 0; } function div(val1,val2) { return val1 / val2; }; function mul(val1,val2) { return val1 * val2; }; var func = (value > this.options.zoom_base)?mul:div; var sgn = (value > this.options.zoom_base)?1:-1; var mltplr = this.options.zoom_delta; var rate = 1; while(math.abs(func(this.options.zoom_base, math.pow(mltplr,rate)) - value) > math.abs(func(this.options.zoom_base, math.pow(mltplr,rate+1)) - value)) { rate++; } return sgn * rate; }, /* update scale info in the container */ update_status: function() { if(!this.options.ui_disabled) { var percent = math.round(100*this.img_object.display_height()/this.img_object.orig_height()); if(percent) { this.zoom_object.html(percent + "%"); } } }, /** * get some information about the image. * currently orig_(width|height), display_(width|height), angle, zoom and src params are supported. * * @param {string} parameter to check * @param {boolean} withoutrotation if param is orig_width or orig_height and this flag is set to true, * method will return original image width without considering rotation. * */ info: function(param, withoutrotation) { if (!param) { return; } switch (param) { case 'orig_width': case 'orig_height': if (withoutrotation) { return (this.img_object.angle() % 180 === 0 ? this.img_object[param]() : param === 'orig_width' ? this.img_object.orig_height() : this.img_object.orig_width()); } else { return this.img_object[param](); } case 'display_width': case 'display_height': case 'angle': return this.img_object[param](); case 'zoom': return this.current_zoom; case 'options': return this.options; case 'src': return this.img_object.object().attr('src'); case 'coords': return { x: this.img_object.x(), y: this.img_object.y() }; } }, /** * callback for handling mousdown event to start dragging image **/ _mousestart: function( e ) { $.ui.mouse.prototype._mousestart.call(this, e); if (this._trigger('onstartdrag', 0, this._getmousecoords(e)) === false) { return false; } /* start drag event*/ this.container.addclass("iviewer_drag_cursor"); //#10: fix movement quirks for ipad this._draginitialized = !(e.originalevent.changedtouches && e.originalevent.changedtouches.length==1); this.dx = e.pagex - this.img_object.x(); this.dy = e.pagey - this.img_object.y(); return true; }, _mousecapture: function( e ) { return true; }, /** * handle mouse move if needed. user can avoid using this callback, because * he can get the same information through public methods. * @param {jquery.event} e */ _handlemousemove: function(e) { this._trigger('onmousemove', e, this._getmousecoords(e)); }, /** * callback for handling mousemove event to drag image **/ _mousedrag: function(e) { $.ui.mouse.prototype._mousedrag.call(this, e); //#10: imitate mousestart, because we can get here without it on ipad for some reason if (!this._draginitialized) { this.dx = e.pagex - this.img_object.x(); this.dy = e.pagey - this.img_object.y(); this._draginitialized = true; } var ltop = e.pagey - this.dy; var lleft = e.pagex - this.dx; this.setcoords(lleft, ltop); this._trigger('ondrag', e, this._getmousecoords(e)); return false; }, /** * callback for handling stop drag **/ _mousestop: function(e) { $.ui.mouse.prototype._mousestop.call(this, e); this.container.removeclass("iviewer_drag_cursor"); this._trigger('onstopdrag', 0, this._getmousecoords(e)); }, _click: function(e) { this._trigger('onclick', 0, this._getmousecoords(e)); }, _dblclick: function(ev) { if (this.options.ondblclick) { this._trigger('ondblclick', 0, this._getmousecoords(ev)); } if (this.options.zoom_on_dblclick) { var container_offset = this.container.offset() , mouse_pos = { x: ev.pagex - container_offset.left, y: ev.pagey - container_offset.top }; this.zoom_by(1, mouse_pos); } }, /** * create zoom buttons info box **/ createui: function() { var me=this; $("
", { 'class': "iviewer_zoom_in iviewer_common iviewer_button"}) .bind('mousedown touchstart',function(){me.zoom_by(1); return false;}) .appendto(this.container); $("
", { 'class': "iviewer_zoom_out iviewer_common iviewer_button"}) .bind('mousedown touchstart',function(){me.zoom_by(- 1); return false;}) .appendto(this.container); $("
", { 'class': "iviewer_zoom_zero iviewer_common iviewer_button"}) .bind('mousedown touchstart',function(){me.set_zoom(100); return false;}) .appendto(this.container); $("
", { 'class': "iviewer_zoom_fit iviewer_common iviewer_button"}) .bind('mousedown touchstart',function(){me.fit(this); return false;}) .appendto(this.container); this.zoom_object = $("
").addclass("iviewer_zoom_status iviewer_common") .appendto(this.container); $("
", { 'class': "iviewer_rotate_left iviewer_common iviewer_button"}) .bind('mousedown touchstart',function(){me.angle(-90); return false;}) .appendto(this.container); $("
", { 'class': "iviewer_rotate_right iviewer_common iviewer_button" }) .bind('mousedown touchstart',function(){me.angle(90); return false;}) .appendto(this.container); this.update_status(); //initial status update } } ); /** * @class $.ui.iviewer.imageobject class represents image and provides public api without * extending image prototype. * @constructor * @param {boolean} do_anim do we want to animate image on dimension changes? */ $.ui.iviewer.imageobject = function(do_anim) { this._img = $("") //this is needed, because chromium sets them auto otherwise .css({ position: "absolute", top :"0px", left: "0px"}); this._loaded = false; this._swapdimensions = false; this._do_anim = do_anim || false; this.x(0, true); this.y(0, true); this.angle(0); }; /** @lends $.ui.iviewer.imageobject.prototype */ (function() { /** * restore initial object state. * * @param {number} w image width. * @param {number} h image height. */ this._reset = function(w, h) { this._angle = 0; this._swapdimensions = false; this.x(0); this.y(0); this.orig_width(w); this.orig_height(h); this.display_width(w); this.display_height(h); }; /** * check if image is loaded. * * @return {boolean} */ this.loaded = function() { return this._loaded; }; /** * load image. * * @param {string} src image url. * @param {function=} loaded function will be called on image load. */ this.load = function(src, loaded, error) { var self = this; loaded = loaded || jquery.noop; this._loaded = false; // #67: don't use image object for loading in case naturalwidth is supported // because later assigning to self._img[0] may result in additional image requesrts. var supportsnaturalwidth = 'naturalwidth' in new image(); var img = supportsnaturalwidth ? self._img[0] : new image(); img.onload = function() { self._loaded = true; if (supportsnaturalwidth) { self._reset(this.naturalwidth, this.naturalheight); } else { self._reset(this.width, this.height); } self._img .removeattr("width") .removeattr("height") .removeattr("style") //max-width is reset, because plugin breaks in the twitter bootstrap otherwise .css({ position: "absolute", top :"0px", left: "0px", maxwidth: "none"}); if (!supportsnaturalwidth) { self._img[0].src = src; } loaded(); }; img.onerror = error; //we need this because sometimes internet explorer 8 fires onload event //right after assignment (synchronously) settimeout(function() { img.src = src; }, 0); this.angle(0); }; this._dimension = function(prefix, name) { var horiz = '_' + prefix + '_' + name, vert = '_' + prefix + '_' + (name === 'height' ? 'width' : 'height'); return setter(function(val) { this[this._swapdimensions ? horiz: vert] = val; }, function() { return this[this._swapdimensions ? horiz: vert]; }); }; /** * getters and setter for common image dimensions. * display_ means real image tag dimensions * orig_ means physical image dimensions. * note, that dimensions are swapped if image is rotated. it necessary, * because as little as possible code should know about rotation. */ this.display_width = this._dimension('display', 'width'), this.display_height = this._dimension('display', 'height'), this.display_diff = function() { return math.floor( this.display_width() - this.display_height() ); }; this.orig_width = this._dimension('orig', 'width'), this.orig_height = this._dimension('orig', 'height'), /** * setter for x coordinate. if image is rotated we need to additionaly shift an * image to map image coordinate to the visual position. * * @param {number} val coordinate value. * @param {boolean} skipcss if true, we only set the value and do not touch the dom. */ this.x = setter(function(val, skipcss) { this._x = val; if (!skipcss) { this._finishanimation(); this._img.css("left",this._x + (this._swapdimensions ? this.display_diff() / 2 : 0) + "px"); } }, function() { return this._x; }); /** * setter for y coordinate. if image is rotated we need to additionaly shift an * image to map image coordinate to the visual position. * * @param {number} val coordinate value. * @param {boolean} skipcss if true, we only set the value and do not touch the dom. */ this.y = setter(function(val, skipcss) { this._y = val; if (!skipcss) { this._finishanimation(); this._img.css("top",this._y - (this._swapdimensions ? this.display_diff() / 2 : 0) + "px"); } }, function() { return this._y; }); /** * perform image rotation. * * @param {number} deg absolute image angle. the method will work with values 0, 90, 180, 270 degrees. */ this.angle = setter(function(deg) { var prevswap = this._swapdimensions; this._angle = deg; this._swapdimensions = deg % 180 !== 0; if (prevswap !== this._swapdimensions) { var verticalmod = this._swapdimensions ? -1 : 1; this.x(this.x() - verticalmod * this.display_diff() / 2, true); this.y(this.y() + verticalmod * this.display_diff() / 2, true); }; var cssval = 'rotate(' + deg + 'deg)', img = this._img; jquery.each(['', '-webkit-', '-moz-', '-o-', '-ms-'], function(i, prefix) { img.css(prefix + 'transform', cssval); }); if (useietransforms) { jquery.each(['-ms-', ''], function(i, prefix) { img.css(prefix + 'filter', ietransforms[deg].filter); }); img.css({ marginleft: ietransforms[deg].marginleft * this.display_diff() / 2, margintop: ietransforms[deg].margintop * this.display_diff() / 2 }); } }, function() { return this._angle; }); /** * map point in the container coordinates to the point in image coordinates. * you will get coordinates of point on image with respect to rotation, * but will be set as if image was not rotated. * so, if image was rotated 90 degrees, it's (0,0) point will be on the * top right corner. * * @param {{x: number, y: number}} point point in container coordinates. * @return {{x: number, y: number}} */ this.tooriginalcoords = function(point) { switch (this.angle()) { case 0: return { x: point.x, y: point.y }; case 90: return { x: point.y, y: this.display_width() - point.x }; case 180: return { x: this.display_width() - point.x, y: this.display_height() - point.y }; case 270: return { x: this.display_height() - point.y, y: point.x }; } }; /** * map point in the image coordinates to the point in container coordinates. * you will get coordinates of point on container with respect to rotation. * note, if image was rotated 90 degrees, it's (0,0) point will be on the * top right corner. * * @param {{x: number, y: number}} point point in container coordinates. * @return {{x: number, y: number}} */ this.torealcoords = function(point) { switch (this.angle()) { case 0: return { x: this.x() + point.x, y: this.y() + point.y }; case 90: return { x: this.x() + this.display_width() - point.y, y: this.y() + point.x}; case 180: return { x: this.x() + this.display_width() - point.x, y: this.y() + this.display_height() - point.y}; case 270: return { x: this.x() + point.y, y: this.y() + this.display_height() - point.x}; } }; /** * @return {jquery} return image node. this is needed to add event handlers. */ this.object = setter(jquery.noop, function() { return this._img; }); /** * change image properties. * * @param {number} disp_w display width; * @param {number} disp_h display height; * @param {number} x * @param {number} y * @param {boolean} skip_animation if true, the animation will be skiped despite the * value set in constructor. * @param {function=} complete call back will be fired when zoom will be complete. */ this.setimageprops = function(disp_w, disp_h, x, y, skip_animation, complete) { complete = complete || jquery.noop; this.display_width(disp_w); this.display_height(disp_h); this.x(x, true); this.y(y, true); var w = this._swapdimensions ? disp_h : disp_w; var h = this._swapdimensions ? disp_w : disp_h; var params = { width: w, height: h, top: y - (this._swapdimensions ? this.display_diff() / 2 : 0) + "px", left: x + (this._swapdimensions ? this.display_diff() / 2 : 0) + "px" }; if (useietransforms) { jquery.extend(params, { marginleft: ietransforms[this.angle()].marginleft * this.display_diff() / 2, margintop: ietransforms[this.angle()].margintop * this.display_diff() / 2 }); } var swapdims = this._swapdimensions, img = this._img; //here we come: another ie oddness. if image is rotated 90 degrees with a filter, than //width and height getters return real width and height of rotated image. the bad news //is that to set height you need to set a width and vice versa. fuck ie. //so, in this case we have to animate width and height manually. if(useietransforms && swapdims) { var ieh = this._img.width(), iew = this._img.height(), iedh = params.height - ieh; iedw = params.width - iew; delete params.width; delete params.height; } if (this._do_anim && !skip_animation) { this._img.stop(true) .animate(params, { duration: 200, complete: complete, step: function(now, fx) { if(useietransforms && swapdims && (fx.prop === 'top')) { var percent = (now - fx.start) / (fx.end - fx.start); img.height(ieh + iedh * percent); img.width(iew + iedw * percent); img.css('top', now); } } }); } else { this._img.css(params); settimeout(complete, 0); //both if branches should behave equally. } }; //if we set image coordinates we need to be sure that no animation is active atm this._finishanimation = function() { this._img.stop(true, true); }; }).apply($.ui.iviewer.imageobject.prototype); var util = { scalevalue: function(value, tozoom) { return value * tozoom / 100; }, descalevalue: function(value, fromzoom) { return value * 100 / fromzoom; } }; } )( jquery, undefined );