jquery.iviewer.js 38 KB

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