jquery.iviewer.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. /*
  2. * iviewer Widget for jQuery UI
  3. * https://github.com/can3p/iviewer
  4. *
  5. * Copyright (c) 2009 - 2013 Dmitry Petrov
  6. * Dual licensed under the MIT license.
  7. * - http://www.opensource.org/licenses/mit-license.php
  8. *
  9. * Author: Dmitry Petrov
  10. * Version: 0.7.11
  11. */
  12. ( function( $, undefined ) {
  13. //this code was taken from the https://github.com/furf/jquery-ui-touch-punch
  14. var mouseEvents = {
  15. touchstart: 'mousedown',
  16. touchmove: 'mousemove',
  17. touchend: 'mouseup'
  18. },
  19. gesturesSupport = 'ongesturestart' in document.createElement('div');
  20. /**
  21. * Convert a touch event to a mouse-like
  22. */
  23. function makeMouseEvent (event) {
  24. var touch = event.originalEvent.changedTouches[0];
  25. return $.extend(event, {
  26. type: mouseEvents[event.type],
  27. which: 1,
  28. pageX: touch.pageX,
  29. pageY: touch.pageY,
  30. screenX: touch.screenX,
  31. screenY: touch.screenY,
  32. clientX: touch.clientX,
  33. clientY: touch.clientY,
  34. isTouchEvent: true
  35. });
  36. }
  37. var mouseProto = $.ui.mouse.prototype,
  38. _mouseInit = $.ui.mouse.prototype._mouseInit;
  39. mouseProto._mouseInit = function() {
  40. var self = this;
  41. self._touchActive = false;
  42. this.element.bind( 'touchstart.' + this.widgetName, function(event) {
  43. if (gesturesSupport && event.originalEvent.touches.length > 1) { return; }
  44. self._touchActive = true;
  45. return self._mouseDown(makeMouseEvent(event));
  46. });
  47. // these delegates are required to keep context
  48. this._mouseMoveDelegate = function(event) {
  49. if (gesturesSupport && event.originalEvent.touches && event.originalEvent.touches.length > 1) { return; }
  50. if (self._touchActive) {
  51. return self._mouseMove(makeMouseEvent(event));
  52. }
  53. };
  54. this._mouseUpDelegate = function(event) {
  55. if (self._touchActive) {
  56. self._touchActive = false;
  57. return self._mouseUp(makeMouseEvent(event));
  58. }
  59. };
  60. $(document)
  61. .bind('touchmove.'+ this.widgetName, this._mouseMoveDelegate)
  62. .bind('touchend.' + this.widgetName, this._mouseUpDelegate);
  63. _mouseInit.apply(this);
  64. };
  65. /**
  66. * Simple implementation of jQuery like getters/setters
  67. * var val = something();
  68. * something(val);
  69. */
  70. var setter = function(setter, getter) {
  71. return function(val) {
  72. if (arguments.length === 0) {
  73. return getter.apply(this);
  74. } else {
  75. setter.apply(this, arguments);
  76. }
  77. }
  78. };
  79. /**
  80. * Internet explorer rotates image relative left top corner, so we should
  81. * shift image when it's rotated.
  82. */
  83. var ieTransforms = {
  84. '0': {
  85. marginLeft: 0,
  86. marginTop: 0,
  87. filter: 'progid:DXImageTransform.Microsoft.Matrix(M11=1, M12=0, M21=0, M22=1, SizingMethod="auto expand")'
  88. },
  89. '90': {
  90. marginLeft: -1,
  91. marginTop: 1,
  92. filter: 'progid:DXImageTransform.Microsoft.Matrix(M11=0, M12=-1, M21=1, M22=0, SizingMethod="auto expand")'
  93. },
  94. '180': {
  95. marginLeft: 0,
  96. marginTop: 0,
  97. filter: 'progid:DXImageTransform.Microsoft.Matrix(M11=-1, M12=0, M21=0, M22=-1, SizingMethod="auto expand")'
  98. },
  99. '270': {
  100. marginLeft: -1,
  101. marginTop: 1,
  102. filter: 'progid:DXImageTransform.Microsoft.Matrix(M11=0, M12=1, M21=-1, M22=0, SizingMethod="auto expand")'
  103. }
  104. },
  105. // this test is the inversion of the css filters test from the modernizr project
  106. useIeTransforms = function() {
  107. var modElem = document.createElement('modernizr'),
  108. mStyle = modElem.style,
  109. omPrefixes = 'Webkit Moz O ms',
  110. domPrefixes = omPrefixes.toLowerCase().split(' '),
  111. props = ("transform" + ' ' + domPrefixes.join("Transform ") + "Transform").split(' ');
  112. /*using 'for' loop instead of 'for in' to avoid issues in IE8*/
  113. for ( var i=0; i< props.length;i++ ) {
  114. var prop = props[i];
  115. if ( prop.indexOf("-") == -1 && mStyle[prop] !== undefined ) {
  116. return false;
  117. }
  118. }
  119. return true;
  120. }();
  121. $.widget( "ui.iviewer", $.ui.mouse, {
  122. widgetEventPrefix: "iviewer",
  123. options : {
  124. /**
  125. * start zoom value for image, not used now
  126. * may be equal to "fit" to fit image into container or scale in %
  127. **/
  128. zoom: "fit",
  129. /**
  130. * base value to scale image
  131. **/
  132. zoom_base: 100,
  133. /**
  134. * maximum zoom
  135. **/
  136. zoom_max: 800,
  137. /**
  138. * minimum zoom
  139. **/
  140. zoom_min: 25,
  141. /**
  142. * base of rate multiplier.
  143. * zoom is calculated by formula: zoom_base * zoom_delta^rate
  144. **/
  145. zoom_delta: 1.4,
  146. /**
  147. * whether the zoom should be animated.
  148. */
  149. zoom_animation: true,
  150. /**
  151. * if true plugin doesn't add its own controls
  152. **/
  153. ui_disabled: false,
  154. /**
  155. * If false mousewheel will be disabled
  156. */
  157. mousewheel: true,
  158. /**
  159. * if false, plugin doesn't bind resize event on window and this must
  160. * be handled manually
  161. **/
  162. update_on_resize: true,
  163. /**
  164. * whether to provide zoom on doubleclick functionality
  165. */
  166. zoom_on_dblclick: true,
  167. /**
  168. * if true the image will fill the container and the image will be distorted
  169. */
  170. fill_container: false,
  171. /**
  172. * event is triggered when zoom value is changed
  173. * @param int new zoom value
  174. * @return boolean if false zoom action is aborted
  175. **/
  176. onZoom: jQuery.noop,
  177. /**
  178. * event is triggered when zoom value is changed after image is set to the new dimensions
  179. * @param int new zoom value
  180. * @return boolean if false zoom action is aborted
  181. **/
  182. onAfterZoom: jQuery.noop,
  183. /**
  184. * event is fired on drag begin
  185. * @param object coords mouse coordinates on the image
  186. * @return boolean if false is returned, drag action is aborted
  187. **/
  188. onStartDrag: jQuery.noop,
  189. /**
  190. * event is fired on drag action
  191. * @param object coords mouse coordinates on the image
  192. **/
  193. onDrag: jQuery.noop,
  194. /**
  195. * event is fired on drag stop
  196. * @param object coords mouse coordinates on the image
  197. **/
  198. onStopDrag: jQuery.noop,
  199. /**
  200. * event is fired when mouse moves over image
  201. * @param object coords mouse coordinates on the image
  202. **/
  203. onMouseMove: jQuery.noop,
  204. /**
  205. * mouse click event
  206. * @param object coords mouse coordinates on the image
  207. **/
  208. onClick: jQuery.noop,
  209. /**
  210. * mouse double click event. If used will delay each click event.
  211. * If double click event was fired, clicks will not.
  212. *
  213. * @param object coords mouse coordinates on the image
  214. **/
  215. onDblClick: null,
  216. /**
  217. * event is fired when image starts to load
  218. */
  219. onStartLoad: null,
  220. /**
  221. * event is fired, when image is loaded and initially positioned
  222. */
  223. onFinishLoad: null,
  224. /**
  225. * event is fired when image load error occurs
  226. */
  227. onErrorLoad: null
  228. },
  229. _create: function() {
  230. var me = this;
  231. //drag variables
  232. this.dx = 0;
  233. this.dy = 0;
  234. /* object containing actual information about image
  235. * @img_object.object - jquery img object
  236. * @img_object.orig_{width|height} - original dimensions
  237. * @img_object.display_{width|height} - actual dimensions
  238. */
  239. this.img_object = {};
  240. this.zoom_object = {}; //object to show zoom status
  241. this._angle = 0;
  242. this.current_zoom = this.options.zoom;
  243. if(this.options.src === null){
  244. return;
  245. }
  246. this.container = this.element;
  247. this._updateContainerInfo();
  248. //init container
  249. this.container.css("overflow","hidden");
  250. if (this.options.update_on_resize == true) {
  251. $(window).resize(function() {
  252. me.update();
  253. });
  254. }
  255. this.img_object = new $.ui.iviewer.ImageObject(this.options.zoom_animation);
  256. if (this.options.mousewheel) {
  257. this.activateMouseWheel(this.options.mousewheel);
  258. }
  259. //bind doubleclick only if callback is not falsy
  260. var useDblClick = !!this.options.onDblClick || this.options.zoom_on_dblclick,
  261. dblClickTimer = null,
  262. clicksNumber = 0;
  263. //init object
  264. this.img_object.object()
  265. .prependTo(this.container);
  266. //all these tricks are needed to fire either click
  267. //or doubleclick events at the same time
  268. if (useDblClick) {
  269. this.img_object.object()
  270. //bind mouse events
  271. .click(function(e){
  272. clicksNumber++;
  273. clearTimeout(dblClickTimer);
  274. dblClickTimer = setTimeout(function() {
  275. clicksNumber = 0;
  276. me._click(e);
  277. }, 300);
  278. })
  279. .dblclick(function(e){
  280. if (clicksNumber !== 2) return;
  281. clearTimeout(dblClickTimer);
  282. clicksNumber = 0;
  283. me._dblclick(e);
  284. });
  285. } else {
  286. this.img_object.object()
  287. .click(function(e){ me._click(e); });
  288. }
  289. this.container.bind('mousemove.iviewer', function(ev) { me._handleMouseMove(ev); });
  290. this.loadImage(this.options.src);
  291. if(!this.options.ui_disabled)
  292. {
  293. this.createui();
  294. }
  295. this.controls = this.container.find('.iviewer_common') || {};
  296. this._mouseInit();
  297. },
  298. destroy: function() {
  299. $.Widget.prototype.destroy.call( this );
  300. this._mouseDestroy();
  301. this.img_object.object().remove();
  302. /*removing the controls on destroy*/
  303. this.controls.remove();
  304. this.container.off('.iviewer');
  305. this.container.css('overflow', ''); //cleanup styles on destroy
  306. },
  307. _updateContainerInfo: function()
  308. {
  309. this.options.height = this.container.height();
  310. this.options.width = this.container.width();
  311. },
  312. /**
  313. * Add or remove the mousewheel effect on the viewer
  314. * @param {boolean} isActive
  315. * Sample : $('#viewer').iviewer('activateMouseWheel', true);
  316. */
  317. activateMouseWheel: function(isActive){
  318. // Remove all the previous event bind on the mousewheel
  319. this.container.unbind('mousewheel.iviewer');
  320. if (gesturesSupport) {
  321. this.img_object.object().unbind('touchstart').unbind('gesturechange.iviewer').unbind('gestureend.iviewer');
  322. }
  323. if (isActive) {
  324. var me = this;
  325. this.container.bind('mousewheel.iviewer', function(ev, delta)
  326. {
  327. //this event is there instead of containing div, because
  328. //at opera it triggers many times on div
  329. var zoom = (delta > 0)?1:-1,
  330. container_offset = me.container.offset(),
  331. mouse_pos = {
  332. //jquery.mousewheel 3.1.0 uses strange MozMousePixelScroll event
  333. //which is not being fixed by jQuery.Event
  334. x: (ev.pageX || ev.originalEvent.pageX) - container_offset.left,
  335. y: (ev.pageY || ev.originalEvent.pageX) - container_offset.top
  336. };
  337. me.zoom_by(zoom, mouse_pos);
  338. return false;
  339. });
  340. if (gesturesSupport) {
  341. var gestureThrottle = +new Date();
  342. var originalScale, originalCenter;
  343. this.img_object.object()
  344. .bind('touchstart', function(ev) {
  345. originalScale = me.current_zoom;
  346. var touches = ev.originalEvent.touches,
  347. container_offset;
  348. if (touches.length == 2) {
  349. container_offset = me.container.offset();
  350. originalCenter = {
  351. x: (touches[0].pageX + touches[1].pageX) / 2 - container_offset.left,
  352. y: (touches[0].pageY + touches[1].pageY) / 2 - container_offset.top
  353. };
  354. } else {
  355. originalCenter = null;
  356. }
  357. }).bind('gesturechange.iviewer', function(ev) {
  358. //do not want to import throttle function from underscore
  359. var d = +new Date();
  360. if ((d - gestureThrottle) < 50) { return; }
  361. gestureThrottle = d;
  362. var zoom = originalScale * ev.originalEvent.scale;
  363. me.set_zoom(zoom, originalCenter);
  364. ev.preventDefault();
  365. }).bind('gestureend.iviewer', function(ev) {
  366. originalCenter = null;
  367. });
  368. }
  369. }
  370. },
  371. update: function()
  372. {
  373. this._updateContainerInfo();
  374. this.setCoords(this.img_object.x(), this.img_object.y());
  375. },
  376. loadImage: function( src )
  377. {
  378. this.current_zoom = this.options.zoom;
  379. var me = this;
  380. this._trigger('onStartLoad', 0, src);
  381. this.container.addClass("iviewer_loading");
  382. this.img_object.load(src, function() {
  383. me._fill_orig_dimensions = { width: me.img_object.orig_width(), height: me.img_object.orig_height() };
  384. me._imageLoaded(src);
  385. }, function() {
  386. me._trigger("onErrorLoad", 0, src);
  387. });
  388. },
  389. _imageLoaded: function(src) {
  390. this.container.removeClass("iviewer_loading");
  391. this.container.addClass("iviewer_cursor");
  392. if(this.options.zoom == "fit"){
  393. this.fit(true);
  394. }
  395. else {
  396. this.set_zoom(this.options.zoom, true);
  397. }
  398. this._trigger('onFinishLoad', 0, src);
  399. if(this.options.fill_container)
  400. {
  401. this.fill_container(true);
  402. }
  403. },
  404. /**
  405. * fits image in the container
  406. *
  407. * @param {boolean} skip_animation
  408. **/
  409. fit: function(skip_animation)
  410. {
  411. var aspect_ratio = this.img_object.orig_width() / this.img_object.orig_height();
  412. var window_ratio = this.options.width / this.options.height;
  413. var choose_left = (aspect_ratio > window_ratio);
  414. var new_zoom = 0;
  415. if(choose_left){
  416. new_zoom = this.options.width / this.img_object.orig_width() * 100;
  417. }
  418. else {
  419. new_zoom = this.options.height / this.img_object.orig_height() * 100;
  420. }
  421. this.set_zoom(new_zoom, skip_animation);
  422. },
  423. /**
  424. * center image in container
  425. **/
  426. center: function()
  427. {
  428. this.setCoords(-Math.round((this.img_object.display_width() - this.options.width)/2),
  429. -Math.round((this.img_object.display_height() - this.options.height)/2));
  430. },
  431. /**
  432. * move a point in container to the center of display area
  433. * @param x a point in container
  434. * @param y a point in container
  435. **/
  436. moveTo: function(x, y)
  437. {
  438. var dx = x-Math.round(this.options.width/2);
  439. var dy = y-Math.round(this.options.height/2);
  440. var new_x = this.img_object.x() - dx;
  441. var new_y = this.img_object.y() - dy;
  442. this.setCoords(new_x, new_y);
  443. },
  444. /**
  445. * Get container offset object.
  446. */
  447. getContainerOffset: function() {
  448. return jQuery.extend({}, this.container.offset());
  449. },
  450. /**
  451. * set coordinates of upper left corner of image object
  452. **/
  453. setCoords: function(x,y)
  454. {
  455. //do nothing while image is being loaded
  456. if(!this.img_object.loaded()) { return; }
  457. var coords = this._correctCoords(x,y);
  458. this.img_object.x(coords.x);
  459. this.img_object.y(coords.y);
  460. },
  461. _correctCoords: function( x, y )
  462. {
  463. x = parseInt(x, 10);
  464. y = parseInt(y, 10);
  465. //check new coordinates to be correct (to be in rect)
  466. if(y > 0){
  467. y = 0;
  468. }
  469. if(x > 0){
  470. x = 0;
  471. }
  472. if(y + this.img_object.display_height() < this.options.height){
  473. y = this.options.height - this.img_object.display_height();
  474. }
  475. if(x + this.img_object.display_width() < this.options.width){
  476. x = this.options.width - this.img_object.display_width();
  477. }
  478. if(this.img_object.display_width() <= this.options.width){
  479. x = -(this.img_object.display_width() - this.options.width)/2;
  480. }
  481. if(this.img_object.display_height() <= this.options.height){
  482. y = -(this.img_object.display_height() - this.options.height)/2;
  483. }
  484. return { x: x, y:y };
  485. },
  486. /**
  487. * convert coordinates on the container to the coordinates on the image (in original size)
  488. *
  489. * @return object with fields x,y according to coordinates or false
  490. * if initial coords are not inside image
  491. **/
  492. containerToImage : function (x,y)
  493. {
  494. var coords = { x : x - this.img_object.x(),
  495. y : y - this.img_object.y()
  496. };
  497. coords = this.img_object.toOriginalCoords(coords);
  498. return { x : util.descaleValue(coords.x, this.current_zoom),
  499. y : util.descaleValue(coords.y, this.current_zoom)
  500. };
  501. },
  502. /**
  503. * convert coordinates on the image (in original size, and zero angle) to the coordinates on the container
  504. *
  505. * @return object with fields x,y according to coordinates
  506. **/
  507. imageToContainer : function (x,y)
  508. {
  509. var coords = {
  510. x : util.scaleValue(x, this.current_zoom),
  511. y : util.scaleValue(y, this.current_zoom)
  512. };
  513. return this.img_object.toRealCoords(coords);
  514. },
  515. /**
  516. * get mouse coordinates on the image
  517. * @param e - object containing pageX and pageY fields, e.g. mouse event object
  518. *
  519. * @return object with fields x,y according to coordinates or false
  520. * if initial coords are not inside image
  521. **/
  522. _getMouseCoords : function(e)
  523. {
  524. var containerOffset = this.container.offset(),
  525. coords = this.containerToImage(e.pageX - containerOffset.left, e.pageY - containerOffset.top);
  526. return coords;
  527. },
  528. /**
  529. * fills container entirely by distorting image
  530. *
  531. * @param {boolean} fill wether to fill the container entirely or not.
  532. **/
  533. fill_container: function(fill)
  534. {
  535. this.options.fill_container = fill;
  536. if(fill)
  537. {
  538. var ratio = this.options.width / this.options.height;
  539. if (ratio > 1)
  540. this.img_object.orig_width(this.img_object.orig_height() * ratio);
  541. else
  542. this.img_object.orig_height(this.img_object.orig_width() * ratio);
  543. }
  544. else
  545. {
  546. this.img_object.orig_width(this._fill_orig_dimensions.width);
  547. this.img_object.orig_height(this._fill_orig_dimensions.height);
  548. }
  549. this.set_zoom(this.current_zoom);
  550. },
  551. /**
  552. * set image scale to the new_zoom
  553. *
  554. * @param {number} new_zoom image scale in %
  555. * @param {boolean} skip_animation
  556. * @param {x: number, y: number} Coordinates of point the should not be moved on zoom. The default is the center of image.
  557. **/
  558. set_zoom: function(new_zoom, skip_animation, zoom_center)
  559. {
  560. if (this._trigger('onZoom', 0, new_zoom) == false) {
  561. return;
  562. }
  563. //do nothing while image is being loaded
  564. if(!this.img_object.loaded()) { return; }
  565. zoom_center = zoom_center || {
  566. x: Math.round(this.options.width/2),
  567. y: Math.round(this.options.height/2)
  568. };
  569. if(new_zoom < this.options.zoom_min)
  570. {
  571. new_zoom = this.options.zoom_min;
  572. }
  573. else if(new_zoom > this.options.zoom_max)
  574. {
  575. new_zoom = this.options.zoom_max;
  576. }
  577. /* we fake these values to make fit zoom properly work */
  578. var old_x, old_y;
  579. if(this.current_zoom == "fit")
  580. {
  581. old_x = zoom_center.x + Math.round(this.img_object.orig_width()/2);
  582. old_y = zoom_center.y + Math.round(this.img_object.orig_height()/2);
  583. this.current_zoom = 100;
  584. }
  585. else {
  586. old_x = -this.img_object.x() + zoom_center.x;
  587. old_y = -this.img_object.y() + zoom_center.y;
  588. }
  589. var new_width = util.scaleValue(this.img_object.orig_width(), new_zoom);
  590. var new_height = util.scaleValue(this.img_object.orig_height(), new_zoom);
  591. var new_x = util.scaleValue( util.descaleValue(old_x, this.current_zoom), new_zoom);
  592. var new_y = util.scaleValue( util.descaleValue(old_y, this.current_zoom), new_zoom);
  593. new_x = zoom_center.x - new_x;
  594. new_y = zoom_center.y - new_y;
  595. new_width = Math.floor(new_width);
  596. new_height = Math.floor(new_height);
  597. new_x = Math.floor(new_x);
  598. new_y = Math.floor(new_y);
  599. this.img_object.display_width(new_width);
  600. this.img_object.display_height(new_height);
  601. var coords = this._correctCoords( new_x, new_y ),
  602. self = this;
  603. this.img_object.setImageProps(new_width, new_height, coords.x, coords.y,
  604. skip_animation, function() {
  605. self._trigger('onAfterZoom', 0, new_zoom );
  606. });
  607. this.current_zoom = new_zoom;
  608. this.update_status();
  609. },
  610. /**
  611. * shows or hides the controls
  612. * controls are shown/hidden based on user input
  613. * @param Boolean flag that specifies whether to show or hide the controls
  614. **/
  615. showControls: function(flag) {
  616. if(flag) {
  617. this.controls.fadeIn();
  618. } else {
  619. this.controls.fadeOut();
  620. }
  621. },
  622. /**
  623. * changes zoom scale by delta
  624. * zoom is calculated by formula: zoom_base * zoom_delta^rate
  625. * @param Integer delta number to add to the current multiplier rate number
  626. * @param {x: number, y: number=} Coordinates of point the should not be moved on zoom.
  627. **/
  628. zoom_by: function(delta, zoom_center)
  629. {
  630. var closest_rate = this.find_closest_zoom_rate(this.current_zoom);
  631. var next_rate = closest_rate + delta;
  632. var next_zoom = this.options.zoom_base * Math.pow(this.options.zoom_delta, next_rate);
  633. if(delta > 0 && next_zoom < this.current_zoom)
  634. {
  635. next_zoom *= this.options.zoom_delta;
  636. }
  637. if(delta < 0 && next_zoom > this.current_zoom)
  638. {
  639. next_zoom /= this.options.zoom_delta;
  640. }
  641. this.set_zoom(next_zoom, undefined, zoom_center);
  642. },
  643. /**
  644. * Rotate image
  645. * @param {num} deg Degrees amount to rotate. Positive values rotate image clockwise.
  646. * Currently 0, 90, 180, 270 and -90, -180, -270 values are supported
  647. *
  648. * @param {boolean} abs If the flag is true if, the deg parameter will be considered as
  649. * a absolute value and relative otherwise.
  650. * @return {num|null} Method will return current image angle if called without any arguments.
  651. **/
  652. angle: function(deg, abs) {
  653. if (arguments.length === 0) { return this.img_object.angle(); }
  654. if (deg < -270 || deg > 270 || deg % 90 !== 0) { return; }
  655. if (!abs) { deg += this.img_object.angle(); }
  656. if (deg < 0) { deg += 360; }
  657. if (deg >= 360) { deg -= 360; }
  658. if (deg === this.img_object.angle()) { return; }
  659. this.img_object.angle(deg);
  660. //the rotate behavior is different in all editors. For now we just center the
  661. //image. However, it will be better to try to keep the position.
  662. this.center();
  663. this._trigger('angle', 0, { angle: this.img_object.angle() });
  664. },
  665. /**
  666. * finds closest multiplier rate for value
  667. * basing on zoom_base and zoom_delta values from settings
  668. * @param Number value zoom value to examine
  669. **/
  670. find_closest_zoom_rate: function(value)
  671. {
  672. if(value == this.options.zoom_base)
  673. {
  674. return 0;
  675. }
  676. function div(val1,val2) { return val1 / val2; };
  677. function mul(val1,val2) { return val1 * val2; };
  678. var func = (value > this.options.zoom_base)?mul:div;
  679. var sgn = (value > this.options.zoom_base)?1:-1;
  680. var mltplr = this.options.zoom_delta;
  681. var rate = 1;
  682. while(Math.abs(func(this.options.zoom_base, Math.pow(mltplr,rate)) - value) >
  683. Math.abs(func(this.options.zoom_base, Math.pow(mltplr,rate+1)) - value))
  684. {
  685. rate++;
  686. }
  687. return sgn * rate;
  688. },
  689. /* update scale info in the container */
  690. update_status: function()
  691. {
  692. if(!this.options.ui_disabled)
  693. {
  694. var percent = Math.round(100*this.img_object.display_height()/this.img_object.orig_height());
  695. if(percent)
  696. {
  697. this.zoom_object.html(percent + "%");
  698. }
  699. }
  700. },
  701. /**
  702. * Get some information about the image.
  703. * Currently orig_(width|height), display_(width|height), angle, zoom and src params are supported.
  704. *
  705. * @param {string} parameter to check
  706. * @param {boolean} withoutRotation if param is orig_width or orig_height and this flag is set to true,
  707. * method will return original image width without considering rotation.
  708. *
  709. */
  710. info: function(param, withoutRotation) {
  711. if (!param) { return; }
  712. switch (param) {
  713. case 'orig_width':
  714. case 'orig_height':
  715. if (withoutRotation) {
  716. return (this.img_object.angle() % 180 === 0 ? this.img_object[param]() :
  717. param === 'orig_width' ? this.img_object.orig_height() :
  718. this.img_object.orig_width());
  719. } else {
  720. return this.img_object[param]();
  721. }
  722. case 'display_width':
  723. case 'display_height':
  724. case 'angle':
  725. return this.img_object[param]();
  726. case 'zoom':
  727. return this.current_zoom;
  728. case 'options':
  729. return this.options;
  730. case 'src':
  731. return this.img_object.object().attr('src');
  732. case 'coords':
  733. return {
  734. x: this.img_object.x(),
  735. y: this.img_object.y()
  736. };
  737. }
  738. },
  739. /**
  740. * callback for handling mousdown event to start dragging image
  741. **/
  742. _mouseStart: function( e )
  743. {
  744. $.ui.mouse.prototype._mouseStart.call(this, e);
  745. if (this._trigger('onStartDrag', 0, this._getMouseCoords(e)) === false) {
  746. return false;
  747. }
  748. /* start drag event*/
  749. this.container.addClass("iviewer_drag_cursor");
  750. //#10: fix movement quirks for ipad
  751. this._dragInitialized = !(e.originalEvent.changedTouches && e.originalEvent.changedTouches.length==1);
  752. this.dx = e.pageX - this.img_object.x();
  753. this.dy = e.pageY - this.img_object.y();
  754. return true;
  755. },
  756. _mouseCapture: function( e ) {
  757. return true;
  758. },
  759. /**
  760. * Handle mouse move if needed. User can avoid using this callback, because
  761. * he can get the same information through public methods.
  762. * @param {jQuery.Event} e
  763. */
  764. _handleMouseMove: function(e) {
  765. this._trigger('onMouseMove', e, this._getMouseCoords(e));
  766. },
  767. /**
  768. * callback for handling mousemove event to drag image
  769. **/
  770. _mouseDrag: function(e)
  771. {
  772. $.ui.mouse.prototype._mouseDrag.call(this, e);
  773. //#10: imitate mouseStart, because we can get here without it on iPad for some reason
  774. if (!this._dragInitialized) {
  775. this.dx = e.pageX - this.img_object.x();
  776. this.dy = e.pageY - this.img_object.y();
  777. this._dragInitialized = true;
  778. }
  779. var ltop = e.pageY - this.dy;
  780. var lleft = e.pageX - this.dx;
  781. this.setCoords(lleft, ltop);
  782. this._trigger('onDrag', e, this._getMouseCoords(e));
  783. return false;
  784. },
  785. /**
  786. * callback for handling stop drag
  787. **/
  788. _mouseStop: function(e)
  789. {
  790. $.ui.mouse.prototype._mouseStop.call(this, e);
  791. this.container.removeClass("iviewer_drag_cursor");
  792. this._trigger('onStopDrag', 0, this._getMouseCoords(e));
  793. },
  794. _click: function(e)
  795. {
  796. this._trigger('onClick', 0, this._getMouseCoords(e));
  797. },
  798. _dblclick: function(ev)
  799. {
  800. if (this.options.onDblClick) {
  801. this._trigger('onDblClick', 0, this._getMouseCoords(ev));
  802. }
  803. if (this.options.zoom_on_dblclick) {
  804. var container_offset = this.container.offset()
  805. , mouse_pos = {
  806. x: ev.pageX - container_offset.left,
  807. y: ev.pageY - container_offset.top
  808. };
  809. this.zoom_by(1, mouse_pos);
  810. }
  811. },
  812. /**
  813. * create zoom buttons info box
  814. **/
  815. createui: function()
  816. {
  817. var me=this;
  818. $("<div>", { 'class': "iviewer_zoom_in iviewer_common iviewer_button"})
  819. .bind('mousedown touchstart',function(){me.zoom_by(1); return false;})
  820. .appendTo(this.container);
  821. $("<div>", { 'class': "iviewer_zoom_out iviewer_common iviewer_button"})
  822. .bind('mousedown touchstart',function(){me.zoom_by(- 1); return false;})
  823. .appendTo(this.container);
  824. $("<div>", { 'class': "iviewer_zoom_zero iviewer_common iviewer_button"})
  825. .bind('mousedown touchstart',function(){me.set_zoom(100); return false;})
  826. .appendTo(this.container);
  827. $("<div>", { 'class': "iviewer_zoom_fit iviewer_common iviewer_button"})
  828. .bind('mousedown touchstart',function(){me.fit(this); return false;})
  829. .appendTo(this.container);
  830. this.zoom_object = $("<div>").addClass("iviewer_zoom_status iviewer_common")
  831. .appendTo(this.container);
  832. $("<div>", { 'class': "iviewer_rotate_left iviewer_common iviewer_button"})
  833. .bind('mousedown touchstart',function(){me.angle(-90); return false;})
  834. .appendTo(this.container);
  835. $("<div>", { 'class': "iviewer_rotate_right iviewer_common iviewer_button" })
  836. .bind('mousedown touchstart',function(){me.angle(90); return false;})
  837. .appendTo(this.container);
  838. this.update_status(); //initial status update
  839. }
  840. } );
  841. /**
  842. * @class $.ui.iviewer.ImageObject Class represents image and provides public api without
  843. * extending image prototype.
  844. * @constructor
  845. * @param {boolean} do_anim Do we want to animate image on dimension changes?
  846. */
  847. $.ui.iviewer.ImageObject = function(do_anim) {
  848. this._img = $("<img>")
  849. //this is needed, because chromium sets them auto otherwise
  850. .css({ position: "absolute", top :"0px", left: "0px"});
  851. this._loaded = false;
  852. this._swapDimensions = false;
  853. this._do_anim = do_anim || false;
  854. this.x(0, true);
  855. this.y(0, true);
  856. this.angle(0);
  857. };
  858. /** @lends $.ui.iviewer.ImageObject.prototype */
  859. (function() {
  860. /**
  861. * Restore initial object state.
  862. *
  863. * @param {number} w Image width.
  864. * @param {number} h Image height.
  865. */
  866. this._reset = function(w, h) {
  867. this._angle = 0;
  868. this._swapDimensions = false;
  869. this.x(0);
  870. this.y(0);
  871. this.orig_width(w);
  872. this.orig_height(h);
  873. this.display_width(w);
  874. this.display_height(h);
  875. };
  876. /**
  877. * Check if image is loaded.
  878. *
  879. * @return {boolean}
  880. */
  881. this.loaded = function() { return this._loaded; };
  882. /**
  883. * Load image.
  884. *
  885. * @param {string} src Image url.
  886. * @param {Function=} loaded Function will be called on image load.
  887. */
  888. this.load = function(src, loaded, error) {
  889. var self = this;
  890. loaded = loaded || jQuery.noop;
  891. this._loaded = false;
  892. // #67: don't use image object for loading in case naturalWidth is supported
  893. // because later assigning to self._img[0] may result in additional image requesrts.
  894. var supportsNaturalWidth = 'naturalWidth' in new Image();
  895. var img = supportsNaturalWidth ? self._img[0] : new Image();
  896. img.onload = function() {
  897. self._loaded = true;
  898. if (supportsNaturalWidth) {
  899. self._reset(this.naturalWidth, this.naturalHeight);
  900. } else {
  901. self._reset(this.width, this.height);
  902. }
  903. self._img
  904. .removeAttr("width")
  905. .removeAttr("height")
  906. .removeAttr("style")
  907. //max-width is reset, because plugin breaks in the twitter bootstrap otherwise
  908. .css({ position: "absolute", top :"0px", left: "0px", maxWidth: "none"});
  909. if (!supportsNaturalWidth) {
  910. self._img[0].src = src;
  911. }
  912. loaded();
  913. };
  914. img.onerror = error;
  915. //we need this because sometimes internet explorer 8 fires onload event
  916. //right after assignment (synchronously)
  917. setTimeout(function() {
  918. img.src = src;
  919. }, 0);
  920. this.angle(0);
  921. };
  922. this._dimension = function(prefix, name) {
  923. var horiz = '_' + prefix + '_' + name,
  924. vert = '_' + prefix + '_' + (name === 'height' ? 'width' : 'height');
  925. return setter(function(val) {
  926. this[this._swapDimensions ? horiz: vert] = val;
  927. },
  928. function() {
  929. return this[this._swapDimensions ? horiz: vert];
  930. });
  931. };
  932. /**
  933. * Getters and setter for common image dimensions.
  934. * display_ means real image tag dimensions
  935. * orig_ means physical image dimensions.
  936. * Note, that dimensions are swapped if image is rotated. It necessary,
  937. * because as little as possible code should know about rotation.
  938. */
  939. this.display_width = this._dimension('display', 'width'),
  940. this.display_height = this._dimension('display', 'height'),
  941. this.display_diff = function() { return Math.floor( this.display_width() - this.display_height() ); };
  942. this.orig_width = this._dimension('orig', 'width'),
  943. this.orig_height = this._dimension('orig', 'height'),
  944. /**
  945. * Setter for X coordinate. If image is rotated we need to additionaly shift an
  946. * image to map image coordinate to the visual position.
  947. *
  948. * @param {number} val Coordinate value.
  949. * @param {boolean} skipCss If true, we only set the value and do not touch the dom.
  950. */
  951. this.x = setter(function(val, skipCss) {
  952. this._x = val;
  953. if (!skipCss) {
  954. this._finishAnimation();
  955. this._img.css("left",this._x + (this._swapDimensions ? this.display_diff() / 2 : 0) + "px");
  956. }
  957. },
  958. function() {
  959. return this._x;
  960. });
  961. /**
  962. * Setter for Y coordinate. If image is rotated we need to additionaly shift an
  963. * image to map image coordinate to the visual position.
  964. *
  965. * @param {number} val Coordinate value.
  966. * @param {boolean} skipCss If true, we only set the value and do not touch the dom.
  967. */
  968. this.y = setter(function(val, skipCss) {
  969. this._y = val;
  970. if (!skipCss) {
  971. this._finishAnimation();
  972. this._img.css("top",this._y - (this._swapDimensions ? this.display_diff() / 2 : 0) + "px");
  973. }
  974. },
  975. function() {
  976. return this._y;
  977. });
  978. /**
  979. * Perform image rotation.
  980. *
  981. * @param {number} deg Absolute image angle. The method will work with values 0, 90, 180, 270 degrees.
  982. */
  983. this.angle = setter(function(deg) {
  984. var prevSwap = this._swapDimensions;
  985. this._angle = deg;
  986. this._swapDimensions = deg % 180 !== 0;
  987. if (prevSwap !== this._swapDimensions) {
  988. var verticalMod = this._swapDimensions ? -1 : 1;
  989. this.x(this.x() - verticalMod * this.display_diff() / 2, true);
  990. this.y(this.y() + verticalMod * this.display_diff() / 2, true);
  991. };
  992. var cssVal = 'rotate(' + deg + 'deg)',
  993. img = this._img;
  994. jQuery.each(['', '-webkit-', '-moz-', '-o-', '-ms-'], function(i, prefix) {
  995. img.css(prefix + 'transform', cssVal);
  996. });
  997. if (useIeTransforms) {
  998. jQuery.each(['-ms-', ''], function(i, prefix) {
  999. img.css(prefix + 'filter', ieTransforms[deg].filter);
  1000. });
  1001. img.css({
  1002. marginLeft: ieTransforms[deg].marginLeft * this.display_diff() / 2,
  1003. marginTop: ieTransforms[deg].marginTop * this.display_diff() / 2
  1004. });
  1005. }
  1006. },
  1007. function() { return this._angle; });
  1008. /**
  1009. * Map point in the container coordinates to the point in image coordinates.
  1010. * You will get coordinates of point on image with respect to rotation,
  1011. * but will be set as if image was not rotated.
  1012. * So, if image was rotated 90 degrees, it's (0,0) point will be on the
  1013. * top right corner.
  1014. *
  1015. * @param {{x: number, y: number}} point Point in container coordinates.
  1016. * @return {{x: number, y: number}}
  1017. */
  1018. this.toOriginalCoords = function(point) {
  1019. switch (this.angle()) {
  1020. case 0: return { x: point.x, y: point.y };
  1021. case 90: return { x: point.y, y: this.display_width() - point.x };
  1022. case 180: return { x: this.display_width() - point.x, y: this.display_height() - point.y };
  1023. case 270: return { x: this.display_height() - point.y, y: point.x };
  1024. }
  1025. };
  1026. /**
  1027. * Map point in the image coordinates to the point in container coordinates.
  1028. * You will get coordinates of point on container with respect to rotation.
  1029. * Note, if image was rotated 90 degrees, it's (0,0) point will be on the
  1030. * top right corner.
  1031. *
  1032. * @param {{x: number, y: number}} point Point in container coordinates.
  1033. * @return {{x: number, y: number}}
  1034. */
  1035. this.toRealCoords = function(point) {
  1036. switch (this.angle()) {
  1037. case 0: return { x: this.x() + point.x, y: this.y() + point.y };
  1038. case 90: return { x: this.x() + this.display_width() - point.y, y: this.y() + point.x};
  1039. case 180: return { x: this.x() + this.display_width() - point.x, y: this.y() + this.display_height() - point.y};
  1040. case 270: return { x: this.x() + point.y, y: this.y() + this.display_height() - point.x};
  1041. }
  1042. };
  1043. /**
  1044. * @return {jQuery} Return image node. this is needed to add event handlers.
  1045. */
  1046. this.object = setter(jQuery.noop,
  1047. function() { return this._img; });
  1048. /**
  1049. * Change image properties.
  1050. *
  1051. * @param {number} disp_w Display width;
  1052. * @param {number} disp_h Display height;
  1053. * @param {number} x
  1054. * @param {number} y
  1055. * @param {boolean} skip_animation If true, the animation will be skiped despite the
  1056. * value set in constructor.
  1057. * @param {Function=} complete Call back will be fired when zoom will be complete.
  1058. */
  1059. this.setImageProps = function(disp_w, disp_h, x, y, skip_animation, complete) {
  1060. complete = complete || jQuery.noop;
  1061. this.display_width(disp_w);
  1062. this.display_height(disp_h);
  1063. this.x(x, true);
  1064. this.y(y, true);
  1065. var w = this._swapDimensions ? disp_h : disp_w;
  1066. var h = this._swapDimensions ? disp_w : disp_h;
  1067. var params = {
  1068. width: w,
  1069. height: h,
  1070. top: y - (this._swapDimensions ? this.display_diff() / 2 : 0) + "px",
  1071. left: x + (this._swapDimensions ? this.display_diff() / 2 : 0) + "px"
  1072. };
  1073. if (useIeTransforms) {
  1074. jQuery.extend(params, {
  1075. marginLeft: ieTransforms[this.angle()].marginLeft * this.display_diff() / 2,
  1076. marginTop: ieTransforms[this.angle()].marginTop * this.display_diff() / 2
  1077. });
  1078. }
  1079. var swapDims = this._swapDimensions,
  1080. img = this._img;
  1081. //here we come: another IE oddness. If image is rotated 90 degrees with a filter, than
  1082. //width and height getters return real width and height of rotated image. The bad news
  1083. //is that to set height you need to set a width and vice versa. Fuck IE.
  1084. //So, in this case we have to animate width and height manually.
  1085. if(useIeTransforms && swapDims) {
  1086. var ieh = this._img.width(),
  1087. iew = this._img.height(),
  1088. iedh = params.height - ieh;
  1089. iedw = params.width - iew;
  1090. delete params.width;
  1091. delete params.height;
  1092. }
  1093. if (this._do_anim && !skip_animation) {
  1094. this._img.stop(true)
  1095. .animate(params, {
  1096. duration: 200,
  1097. complete: complete,
  1098. step: function(now, fx) {
  1099. if(useIeTransforms && swapDims && (fx.prop === 'top')) {
  1100. var percent = (now - fx.start) / (fx.end - fx.start);
  1101. img.height(ieh + iedh * percent);
  1102. img.width(iew + iedw * percent);
  1103. img.css('top', now);
  1104. }
  1105. }
  1106. });
  1107. } else {
  1108. this._img.css(params);
  1109. setTimeout(complete, 0); //both if branches should behave equally.
  1110. }
  1111. };
  1112. //if we set image coordinates we need to be sure that no animation is active atm
  1113. this._finishAnimation = function() {
  1114. this._img.stop(true, true);
  1115. };
  1116. }).apply($.ui.iviewer.ImageObject.prototype);
  1117. var util = {
  1118. scaleValue: function(value, toZoom)
  1119. {
  1120. return value * toZoom / 100;
  1121. },
  1122. descaleValue: function(value, fromZoom)
  1123. {
  1124. return value * 100 / fromZoom;
  1125. }
  1126. };
  1127. } )( jQuery, undefined );