国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

3762 рядки
106KB

  1. /*!
  2. * Cropper v4.0.0
  3. * https://github.com/fengyuanchen/cropper
  4. *
  5. * Copyright (c) 2014-2018 Chen Fengyuan
  6. * Released under the MIT license
  7. *
  8. * Date: 2018-04-01T06:27:27.267Z
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
  12. typeof define === 'function' && define.amd ? define(['jquery'], factory) :
  13. (factory(global.jQuery));
  14. }(this, (function ($) { 'use strict';
  15. $ = $ && $.hasOwnProperty('default') ? $['default'] : $;
  16. var IN_BROWSER = typeof window !== 'undefined';
  17. var WINDOW = IN_BROWSER ? window : {};
  18. var NAMESPACE = 'cropper';
  19. // Actions
  20. var ACTION_ALL = 'all';
  21. var ACTION_CROP = 'crop';
  22. var ACTION_MOVE = 'move';
  23. var ACTION_ZOOM = 'zoom';
  24. var ACTION_EAST = 'e';
  25. var ACTION_WEST = 'w';
  26. var ACTION_SOUTH = 's';
  27. var ACTION_NORTH = 'n';
  28. var ACTION_NORTH_EAST = 'ne';
  29. var ACTION_NORTH_WEST = 'nw';
  30. var ACTION_SOUTH_EAST = 'se';
  31. var ACTION_SOUTH_WEST = 'sw';
  32. // Classes
  33. var CLASS_CROP = NAMESPACE + '-crop';
  34. var CLASS_DISABLED = NAMESPACE + '-disabled';
  35. var CLASS_HIDDEN = NAMESPACE + '-hidden';
  36. var CLASS_HIDE = NAMESPACE + '-hide';
  37. var CLASS_INVISIBLE = NAMESPACE + '-invisible';
  38. var CLASS_MODAL = NAMESPACE + '-modal';
  39. var CLASS_MOVE = NAMESPACE + '-move';
  40. // Data keys
  41. var DATA_ACTION = 'action';
  42. var DATA_PREVIEW = 'preview';
  43. // Drag modes
  44. var DRAG_MODE_CROP = 'crop';
  45. var DRAG_MODE_MOVE = 'move';
  46. var DRAG_MODE_NONE = 'none';
  47. // Events
  48. var EVENT_CROP = 'crop';
  49. var EVENT_CROP_END = 'cropend';
  50. var EVENT_CROP_MOVE = 'cropmove';
  51. var EVENT_CROP_START = 'cropstart';
  52. var EVENT_DBLCLICK = 'dblclick';
  53. var EVENT_LOAD = 'load';
  54. var EVENT_POINTER_DOWN = WINDOW.PointerEvent ? 'pointerdown' : 'touchstart mousedown';
  55. var EVENT_POINTER_MOVE = WINDOW.PointerEvent ? 'pointermove' : 'touchmove mousemove';
  56. var EVENT_POINTER_UP = WINDOW.PointerEvent ? 'pointerup pointercancel' : 'touchend touchcancel mouseup';
  57. var EVENT_READY = 'ready';
  58. var EVENT_RESIZE = 'resize';
  59. var EVENT_WHEEL = 'wheel mousewheel DOMMouseScroll';
  60. var EVENT_ZOOM = 'zoom';
  61. // RegExps
  62. var REGEXP_ACTIONS = /^(?:e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/;
  63. var REGEXP_DATA_URL = /^data:/;
  64. var REGEXP_DATA_URL_JPEG = /^data:image\/jpeg;base64,/;
  65. var REGEXP_TAG_NAME = /^(?:img|canvas)$/i;
  66. var DEFAULTS = {
  67. // Define the view mode of the cropper
  68. viewMode: 0, // 0, 1, 2, 3
  69. // Define the dragging mode of the cropper
  70. dragMode: DRAG_MODE_CROP, // 'crop', 'move' or 'none'
  71. // Define the aspect ratio of the crop box
  72. aspectRatio: NaN,
  73. // An object with the previous cropping result data
  74. data: null,
  75. // A selector for adding extra containers to preview
  76. preview: '',
  77. // Re-render the cropper when resize the window
  78. responsive: true,
  79. // Restore the cropped area after resize the window
  80. restore: true,
  81. // Check if the current image is a cross-origin image
  82. checkCrossOrigin: true,
  83. // Check the current image's Exif Orientation information
  84. checkOrientation: true,
  85. // Show the black modal
  86. modal: true,
  87. // Show the dashed lines for guiding
  88. guides: true,
  89. // Show the center indicator for guiding
  90. center: true,
  91. // Show the white modal to highlight the crop box
  92. highlight: true,
  93. // Show the grid background
  94. background: true,
  95. // Enable to crop the image automatically when initialize
  96. autoCrop: true,
  97. // Define the percentage of automatic cropping area when initializes
  98. autoCropArea: 0.8,
  99. // Enable to move the image
  100. movable: true,
  101. // Enable to rotate the image
  102. rotatable: true,
  103. // Enable to scale the image
  104. scalable: true,
  105. // Enable to zoom the image
  106. zoomable: true,
  107. // Enable to zoom the image by dragging touch
  108. zoomOnTouch: true,
  109. // Enable to zoom the image by wheeling mouse
  110. zoomOnWheel: true,
  111. // Define zoom ratio when zoom the image by wheeling mouse
  112. wheelZoomRatio: 0.1,
  113. // Enable to move the crop box
  114. cropBoxMovable: true,
  115. // Enable to resize the crop box
  116. cropBoxResizable: true,
  117. // Toggle drag mode between "crop" and "move" when click twice on the cropper
  118. toggleDragModeOnDblclick: true,
  119. // Size limitation
  120. minCanvasWidth: 0,
  121. minCanvasHeight: 0,
  122. minCropBoxWidth: 0,
  123. minCropBoxHeight: 0,
  124. minContainerWidth: 200,
  125. minContainerHeight: 100,
  126. // Shortcuts of events
  127. ready: null,
  128. cropstart: null,
  129. cropmove: null,
  130. cropend: null,
  131. crop: null,
  132. zoom: null
  133. };
  134. var TEMPLATE = '<div class="cropper-container" touch-action="none">' + '<div class="cropper-wrap-box">' + '<div class="cropper-canvas"></div>' + '</div>' + '<div class="cropper-drag-box"></div>' + '<div class="cropper-crop-box">' + '<span class="cropper-view-box"></span>' + '<span class="cropper-dashed dashed-h"></span>' + '<span class="cropper-dashed dashed-v"></span>' + '<span class="cropper-center"></span>' + '<span class="cropper-face"></span>' + '<span class="cropper-line line-e" data-action="e"></span>' + '<span class="cropper-line line-n" data-action="n"></span>' + '<span class="cropper-line line-w" data-action="w"></span>' + '<span class="cropper-line line-s" data-action="s"></span>' + '<span class="cropper-point point-e" data-action="e"></span>' + '<span class="cropper-point point-n" data-action="n"></span>' + '<span class="cropper-point point-w" data-action="w"></span>' + '<span class="cropper-point point-s" data-action="s"></span>' + '<span class="cropper-point point-ne" data-action="ne"></span>' + '<span class="cropper-point point-nw" data-action="nw"></span>' + '<span class="cropper-point point-sw" data-action="sw"></span>' + '<span class="cropper-point point-se" data-action="se"></span>' + '</div>' + '</div>';
  135. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  136. return typeof obj;
  137. } : function (obj) {
  138. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  139. };
  140. var classCallCheck = function (instance, Constructor) {
  141. if (!(instance instanceof Constructor)) {
  142. throw new TypeError("Cannot call a class as a function");
  143. }
  144. };
  145. var createClass = function () {
  146. function defineProperties(target, props) {
  147. for (var i = 0; i < props.length; i++) {
  148. var descriptor = props[i];
  149. descriptor.enumerable = descriptor.enumerable || false;
  150. descriptor.configurable = true;
  151. if ("value" in descriptor) descriptor.writable = true;
  152. Object.defineProperty(target, descriptor.key, descriptor);
  153. }
  154. }
  155. return function (Constructor, protoProps, staticProps) {
  156. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  157. if (staticProps) defineProperties(Constructor, staticProps);
  158. return Constructor;
  159. };
  160. }();
  161. var toConsumableArray = function (arr) {
  162. if (Array.isArray(arr)) {
  163. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  164. return arr2;
  165. } else {
  166. return Array.from(arr);
  167. }
  168. };
  169. /**
  170. * Check if the given value is not a number.
  171. */
  172. var isNaN = Number.isNaN || WINDOW.isNaN;
  173. /**
  174. * Check if the given value is a number.
  175. * @param {*} value - The value to check.
  176. * @returns {boolean} Returns `true` if the given value is a number, else `false`.
  177. */
  178. function isNumber(value) {
  179. return typeof value === 'number' && !isNaN(value);
  180. }
  181. /**
  182. * Check if the given value is undefined.
  183. * @param {*} value - The value to check.
  184. * @returns {boolean} Returns `true` if the given value is undefined, else `false`.
  185. */
  186. function isUndefined(value) {
  187. return typeof value === 'undefined';
  188. }
  189. /**
  190. * Check if the given value is an object.
  191. * @param {*} value - The value to check.
  192. * @returns {boolean} Returns `true` if the given value is an object, else `false`.
  193. */
  194. function isObject(value) {
  195. return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null;
  196. }
  197. var hasOwnProperty = Object.prototype.hasOwnProperty;
  198. /**
  199. * Check if the given value is a plain object.
  200. * @param {*} value - The value to check.
  201. * @returns {boolean} Returns `true` if the given value is a plain object, else `false`.
  202. */
  203. function isPlainObject(value) {
  204. if (!isObject(value)) {
  205. return false;
  206. }
  207. try {
  208. var _constructor = value.constructor;
  209. var prototype = _constructor.prototype;
  210. return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf');
  211. } catch (e) {
  212. return false;
  213. }
  214. }
  215. /**
  216. * Check if the given value is a function.
  217. * @param {*} value - The value to check.
  218. * @returns {boolean} Returns `true` if the given value is a function, else `false`.
  219. */
  220. function isFunction(value) {
  221. return typeof value === 'function';
  222. }
  223. /**
  224. * Iterate the given data.
  225. * @param {*} data - The data to iterate.
  226. * @param {Function} callback - The process function for each element.
  227. * @returns {*} The original data.
  228. */
  229. function forEach(data, callback) {
  230. if (data && isFunction(callback)) {
  231. if (Array.isArray(data) || isNumber(data.length) /* array-like */) {
  232. var length = data.length;
  233. var i = void 0;
  234. for (i = 0; i < length; i += 1) {
  235. if (callback.call(data, data[i], i, data) === false) {
  236. break;
  237. }
  238. }
  239. } else if (isObject(data)) {
  240. Object.keys(data).forEach(function (key) {
  241. callback.call(data, data[key], key, data);
  242. });
  243. }
  244. }
  245. return data;
  246. }
  247. /**
  248. * Extend the given object.
  249. * @param {*} obj - The object to be extended.
  250. * @param {*} args - The rest objects which will be merged to the first object.
  251. * @returns {Object} The extended object.
  252. */
  253. var assign = Object.assign || function assign(obj) {
  254. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  255. args[_key - 1] = arguments[_key];
  256. }
  257. if (isObject(obj) && args.length > 0) {
  258. args.forEach(function (arg) {
  259. if (isObject(arg)) {
  260. Object.keys(arg).forEach(function (key) {
  261. obj[key] = arg[key];
  262. });
  263. }
  264. });
  265. }
  266. return obj;
  267. };
  268. var REGEXP_DECIMALS = /\.\d*(?:0|9){12}\d*$/i;
  269. /**
  270. * Normalize decimal number.
  271. * Check out {@link http://0.30000000000000004.com/}
  272. * @param {number} value - The value to normalize.
  273. * @param {number} [times=100000000000] - The times for normalizing.
  274. * @returns {number} Returns the normalized number.
  275. */
  276. function normalizeDecimalNumber(value) {
  277. var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;
  278. return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;
  279. }
  280. var REGEXP_SUFFIX = /^(?:width|height|left|top|marginLeft|marginTop)$/;
  281. /**
  282. * Apply styles to the given element.
  283. * @param {Element} element - The target element.
  284. * @param {Object} styles - The styles for applying.
  285. */
  286. function setStyle(element, styles) {
  287. var style = element.style;
  288. forEach(styles, function (value, property) {
  289. if (REGEXP_SUFFIX.test(property) && isNumber(value)) {
  290. value += 'px';
  291. }
  292. style[property] = value;
  293. });
  294. }
  295. /**
  296. * Check if the given element has a special class.
  297. * @param {Element} element - The element to check.
  298. * @param {string} value - The class to search.
  299. * @returns {boolean} Returns `true` if the special class was found.
  300. */
  301. function hasClass(element, value) {
  302. return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1;
  303. }
  304. /**
  305. * Add classes to the given element.
  306. * @param {Element} element - The target element.
  307. * @param {string} value - The classes to be added.
  308. */
  309. function addClass(element, value) {
  310. if (!value) {
  311. return;
  312. }
  313. if (isNumber(element.length)) {
  314. forEach(element, function (elem) {
  315. addClass(elem, value);
  316. });
  317. return;
  318. }
  319. if (element.classList) {
  320. element.classList.add(value);
  321. return;
  322. }
  323. var className = element.className.trim();
  324. if (!className) {
  325. element.className = value;
  326. } else if (className.indexOf(value) < 0) {
  327. element.className = className + ' ' + value;
  328. }
  329. }
  330. /**
  331. * Remove classes from the given element.
  332. * @param {Element} element - The target element.
  333. * @param {string} value - The classes to be removed.
  334. */
  335. function removeClass(element, value) {
  336. if (!value) {
  337. return;
  338. }
  339. if (isNumber(element.length)) {
  340. forEach(element, function (elem) {
  341. removeClass(elem, value);
  342. });
  343. return;
  344. }
  345. if (element.classList) {
  346. element.classList.remove(value);
  347. return;
  348. }
  349. if (element.className.indexOf(value) >= 0) {
  350. element.className = element.className.replace(value, '');
  351. }
  352. }
  353. /**
  354. * Add or remove classes from the given element.
  355. * @param {Element} element - The target element.
  356. * @param {string} value - The classes to be toggled.
  357. * @param {boolean} added - Add only.
  358. */
  359. function toggleClass(element, value, added) {
  360. if (!value) {
  361. return;
  362. }
  363. if (isNumber(element.length)) {
  364. forEach(element, function (elem) {
  365. toggleClass(elem, value, added);
  366. });
  367. return;
  368. }
  369. // IE10-11 doesn't support the second parameter of `classList.toggle`
  370. if (added) {
  371. addClass(element, value);
  372. } else {
  373. removeClass(element, value);
  374. }
  375. }
  376. var REGEXP_HYPHENATE = /([a-z\d])([A-Z])/g;
  377. /**
  378. * Transform the given string from camelCase to kebab-case
  379. * @param {string} value - The value to transform.
  380. * @returns {string} The transformed value.
  381. */
  382. function hyphenate(value) {
  383. return value.replace(REGEXP_HYPHENATE, '$1-$2').toLowerCase();
  384. }
  385. /**
  386. * Get data from the given element.
  387. * @param {Element} element - The target element.
  388. * @param {string} name - The data key to get.
  389. * @returns {string} The data value.
  390. */
  391. function getData(element, name) {
  392. if (isObject(element[name])) {
  393. return element[name];
  394. } else if (element.dataset) {
  395. return element.dataset[name];
  396. }
  397. return element.getAttribute('data-' + hyphenate(name));
  398. }
  399. /**
  400. * Set data to the given element.
  401. * @param {Element} element - The target element.
  402. * @param {string} name - The data key to set.
  403. * @param {string} data - The data value.
  404. */
  405. function setData(element, name, data) {
  406. if (isObject(data)) {
  407. element[name] = data;
  408. } else if (element.dataset) {
  409. element.dataset[name] = data;
  410. } else {
  411. element.setAttribute('data-' + hyphenate(name), data);
  412. }
  413. }
  414. /**
  415. * Remove data from the given element.
  416. * @param {Element} element - The target element.
  417. * @param {string} name - The data key to remove.
  418. */
  419. function removeData(element, name) {
  420. if (isObject(element[name])) {
  421. try {
  422. delete element[name];
  423. } catch (e) {
  424. element[name] = undefined;
  425. }
  426. } else if (element.dataset) {
  427. // #128 Safari not allows to delete dataset property
  428. try {
  429. delete element.dataset[name];
  430. } catch (e) {
  431. element.dataset[name] = undefined;
  432. }
  433. } else {
  434. element.removeAttribute('data-' + hyphenate(name));
  435. }
  436. }
  437. var REGEXP_SPACES = /\s\s*/;
  438. var onceSupported = function () {
  439. var supported = false;
  440. if (IN_BROWSER) {
  441. var once = false;
  442. var listener = function listener() {};
  443. var options = Object.defineProperty({}, 'once', {
  444. get: function get$$1() {
  445. supported = true;
  446. return once;
  447. },
  448. /**
  449. * This setter can fix a `TypeError` in strict mode
  450. * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only}
  451. * @param {boolean} value - The value to set
  452. */
  453. set: function set$$1(value) {
  454. once = value;
  455. }
  456. });
  457. WINDOW.addEventListener('test', listener, options);
  458. WINDOW.removeEventListener('test', listener, options);
  459. }
  460. return supported;
  461. }();
  462. /**
  463. * Remove event listener from the target element.
  464. * @param {Element} element - The event target.
  465. * @param {string} type - The event type(s).
  466. * @param {Function} listener - The event listener.
  467. * @param {Object} options - The event options.
  468. */
  469. function removeListener(element, type, listener) {
  470. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  471. var handler = listener;
  472. type.trim().split(REGEXP_SPACES).forEach(function (event) {
  473. if (!onceSupported) {
  474. var listeners = element.listeners;
  475. if (listeners && listeners[event] && listeners[event][listener]) {
  476. handler = listeners[event][listener];
  477. delete listeners[event][listener];
  478. if (Object.keys(listeners[event]).length === 0) {
  479. delete listeners[event];
  480. }
  481. if (Object.keys(listeners).length === 0) {
  482. delete element.listeners;
  483. }
  484. }
  485. }
  486. element.removeEventListener(event, handler, options);
  487. });
  488. }
  489. /**
  490. * Add event listener to the target element.
  491. * @param {Element} element - The event target.
  492. * @param {string} type - The event type(s).
  493. * @param {Function} listener - The event listener.
  494. * @param {Object} options - The event options.
  495. */
  496. function addListener(element, type, listener) {
  497. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  498. var _handler = listener;
  499. type.trim().split(REGEXP_SPACES).forEach(function (event) {
  500. if (options.once && !onceSupported) {
  501. var _element$listeners = element.listeners,
  502. listeners = _element$listeners === undefined ? {} : _element$listeners;
  503. _handler = function handler() {
  504. for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  505. args[_key2] = arguments[_key2];
  506. }
  507. delete listeners[event][listener];
  508. element.removeEventListener(event, _handler, options);
  509. listener.apply(element, args);
  510. };
  511. if (!listeners[event]) {
  512. listeners[event] = {};
  513. }
  514. if (listeners[event][listener]) {
  515. element.removeEventListener(event, listeners[event][listener], options);
  516. }
  517. listeners[event][listener] = _handler;
  518. element.listeners = listeners;
  519. }
  520. element.addEventListener(event, _handler, options);
  521. });
  522. }
  523. /**
  524. * Dispatch event on the target element.
  525. * @param {Element} element - The event target.
  526. * @param {string} type - The event type(s).
  527. * @param {Object} data - The additional event data.
  528. * @returns {boolean} Indicate if the event is default prevented or not.
  529. */
  530. function dispatchEvent(element, type, data) {
  531. var event = void 0;
  532. // Event and CustomEvent on IE9-11 are global objects, not constructors
  533. if (isFunction(Event) && isFunction(CustomEvent)) {
  534. event = new CustomEvent(type, {
  535. detail: data,
  536. bubbles: true,
  537. cancelable: true
  538. });
  539. } else {
  540. event = document.createEvent('CustomEvent');
  541. event.initCustomEvent(type, true, true, data);
  542. }
  543. return element.dispatchEvent(event);
  544. }
  545. /**
  546. * Get the offset base on the document.
  547. * @param {Element} element - The target element.
  548. * @returns {Object} The offset data.
  549. */
  550. function getOffset(element) {
  551. var box = element.getBoundingClientRect();
  552. return {
  553. left: box.left + (window.pageXOffset - document.documentElement.clientLeft),
  554. top: box.top + (window.pageYOffset - document.documentElement.clientTop)
  555. };
  556. }
  557. var location = WINDOW.location;
  558. var REGEXP_ORIGINS = /^(https?:)\/\/([^:/?#]+):?(\d*)/i;
  559. /**
  560. * Check if the given URL is a cross origin URL.
  561. * @param {string} url - The target URL.
  562. * @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`.
  563. */
  564. function isCrossOriginURL(url) {
  565. var parts = url.match(REGEXP_ORIGINS);
  566. return parts && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port);
  567. }
  568. /**
  569. * Add timestamp to the given URL.
  570. * @param {string} url - The target URL.
  571. * @returns {string} The result URL.
  572. */
  573. function addTimestamp(url) {
  574. var timestamp = 'timestamp=' + new Date().getTime();
  575. return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp;
  576. }
  577. /**
  578. * Get transforms base on the given object.
  579. * @param {Object} obj - The target object.
  580. * @returns {string} A string contains transform values.
  581. */
  582. function getTransforms(_ref) {
  583. var rotate = _ref.rotate,
  584. scaleX = _ref.scaleX,
  585. scaleY = _ref.scaleY,
  586. translateX = _ref.translateX,
  587. translateY = _ref.translateY;
  588. var values = [];
  589. if (isNumber(translateX) && translateX !== 0) {
  590. values.push('translateX(' + translateX + 'px)');
  591. }
  592. if (isNumber(translateY) && translateY !== 0) {
  593. values.push('translateY(' + translateY + 'px)');
  594. }
  595. // Rotate should come first before scale to match orientation transform
  596. if (isNumber(rotate) && rotate !== 0) {
  597. values.push('rotate(' + rotate + 'deg)');
  598. }
  599. if (isNumber(scaleX) && scaleX !== 1) {
  600. values.push('scaleX(' + scaleX + ')');
  601. }
  602. if (isNumber(scaleY) && scaleY !== 1) {
  603. values.push('scaleY(' + scaleY + ')');
  604. }
  605. var transform = values.length ? values.join(' ') : 'none';
  606. return {
  607. WebkitTransform: transform,
  608. msTransform: transform,
  609. transform: transform
  610. };
  611. }
  612. /**
  613. * Get the max ratio of a group of pointers.
  614. * @param {string} pointers - The target pointers.
  615. * @returns {number} The result ratio.
  616. */
  617. function getMaxZoomRatio(pointers) {
  618. var pointers2 = assign({}, pointers);
  619. var ratios = [];
  620. forEach(pointers, function (pointer, pointerId) {
  621. delete pointers2[pointerId];
  622. forEach(pointers2, function (pointer2) {
  623. var x1 = Math.abs(pointer.startX - pointer2.startX);
  624. var y1 = Math.abs(pointer.startY - pointer2.startY);
  625. var x2 = Math.abs(pointer.endX - pointer2.endX);
  626. var y2 = Math.abs(pointer.endY - pointer2.endY);
  627. var z1 = Math.sqrt(x1 * x1 + y1 * y1);
  628. var z2 = Math.sqrt(x2 * x2 + y2 * y2);
  629. var ratio = (z2 - z1) / z1;
  630. ratios.push(ratio);
  631. });
  632. });
  633. ratios.sort(function (a, b) {
  634. return Math.abs(a) < Math.abs(b);
  635. });
  636. return ratios[0];
  637. }
  638. /**
  639. * Get a pointer from an event object.
  640. * @param {Object} event - The target event object.
  641. * @param {boolean} endOnly - Indicates if only returns the end point coordinate or not.
  642. * @returns {Object} The result pointer contains start and/or end point coordinates.
  643. */
  644. function getPointer(_ref2, endOnly) {
  645. var pageX = _ref2.pageX,
  646. pageY = _ref2.pageY;
  647. var end = {
  648. endX: pageX,
  649. endY: pageY
  650. };
  651. return endOnly ? end : assign({
  652. startX: pageX,
  653. startY: pageY
  654. }, end);
  655. }
  656. /**
  657. * Get the center point coordinate of a group of pointers.
  658. * @param {Object} pointers - The target pointers.
  659. * @returns {Object} The center point coordinate.
  660. */
  661. function getPointersCenter(pointers) {
  662. var pageX = 0;
  663. var pageY = 0;
  664. var count = 0;
  665. forEach(pointers, function (_ref3) {
  666. var startX = _ref3.startX,
  667. startY = _ref3.startY;
  668. pageX += startX;
  669. pageY += startY;
  670. count += 1;
  671. });
  672. pageX /= count;
  673. pageY /= count;
  674. return {
  675. pageX: pageX,
  676. pageY: pageY
  677. };
  678. }
  679. /**
  680. * Check if the given value is a finite number.
  681. */
  682. var isFinite = Number.isFinite || WINDOW.isFinite;
  683. /**
  684. * Get the max sizes in a rectangle under the given aspect ratio.
  685. * @param {Object} data - The original sizes.
  686. * @param {string} [type='contain'] - The adjust type.
  687. * @returns {Object} The result sizes.
  688. */
  689. function getAdjustedSizes(_ref4) // or 'cover'
  690. {
  691. var aspectRatio = _ref4.aspectRatio,
  692. height = _ref4.height,
  693. width = _ref4.width;
  694. var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain';
  695. var isValidNumber = function isValidNumber(value) {
  696. return isFinite(value) && value > 0;
  697. };
  698. if (isValidNumber(width) && isValidNumber(height)) {
  699. var adjustedWidth = height * aspectRatio;
  700. if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {
  701. height = width / aspectRatio;
  702. } else {
  703. width = height * aspectRatio;
  704. }
  705. } else if (isValidNumber(width)) {
  706. height = width / aspectRatio;
  707. } else if (isValidNumber(height)) {
  708. width = height * aspectRatio;
  709. }
  710. return {
  711. width: width,
  712. height: height
  713. };
  714. }
  715. /**
  716. * Get the new sizes of a rectangle after rotated.
  717. * @param {Object} data - The original sizes.
  718. * @returns {Object} The result sizes.
  719. */
  720. function getRotatedSizes(_ref5) {
  721. var width = _ref5.width,
  722. height = _ref5.height,
  723. degree = _ref5.degree;
  724. degree = Math.abs(degree) % 180;
  725. if (degree === 90) {
  726. return {
  727. width: height,
  728. height: width
  729. };
  730. }
  731. var arc = degree % 90 * Math.PI / 180;
  732. var sinArc = Math.sin(arc);
  733. var cosArc = Math.cos(arc);
  734. var newWidth = width * cosArc + height * sinArc;
  735. var newHeight = width * sinArc + height * cosArc;
  736. return degree > 90 ? {
  737. width: newHeight,
  738. height: newWidth
  739. } : {
  740. width: newWidth,
  741. height: newHeight
  742. };
  743. }
  744. /**
  745. * Get a canvas which drew the given image.
  746. * @param {HTMLImageElement} image - The image for drawing.
  747. * @param {Object} imageData - The image data.
  748. * @param {Object} canvasData - The canvas data.
  749. * @param {Object} options - The options.
  750. * @returns {HTMLCanvasElement} The result canvas.
  751. */
  752. function getSourceCanvas(image, _ref6, _ref7, _ref8) {
  753. var imageAspectRatio = _ref6.aspectRatio,
  754. imageNaturalWidth = _ref6.naturalWidth,
  755. imageNaturalHeight = _ref6.naturalHeight,
  756. _ref6$rotate = _ref6.rotate,
  757. rotate = _ref6$rotate === undefined ? 0 : _ref6$rotate,
  758. _ref6$scaleX = _ref6.scaleX,
  759. scaleX = _ref6$scaleX === undefined ? 1 : _ref6$scaleX,
  760. _ref6$scaleY = _ref6.scaleY,
  761. scaleY = _ref6$scaleY === undefined ? 1 : _ref6$scaleY;
  762. var aspectRatio = _ref7.aspectRatio,
  763. naturalWidth = _ref7.naturalWidth,
  764. naturalHeight = _ref7.naturalHeight;
  765. var _ref8$fillColor = _ref8.fillColor,
  766. fillColor = _ref8$fillColor === undefined ? 'transparent' : _ref8$fillColor,
  767. _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled,
  768. imageSmoothingEnabled = _ref8$imageSmoothingE === undefined ? true : _ref8$imageSmoothingE,
  769. _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality,
  770. imageSmoothingQuality = _ref8$imageSmoothingQ === undefined ? 'low' : _ref8$imageSmoothingQ,
  771. _ref8$maxWidth = _ref8.maxWidth,
  772. maxWidth = _ref8$maxWidth === undefined ? Infinity : _ref8$maxWidth,
  773. _ref8$maxHeight = _ref8.maxHeight,
  774. maxHeight = _ref8$maxHeight === undefined ? Infinity : _ref8$maxHeight,
  775. _ref8$minWidth = _ref8.minWidth,
  776. minWidth = _ref8$minWidth === undefined ? 0 : _ref8$minWidth,
  777. _ref8$minHeight = _ref8.minHeight,
  778. minHeight = _ref8$minHeight === undefined ? 0 : _ref8$minHeight;
  779. var canvas = document.createElement('canvas');
  780. var context = canvas.getContext('2d');
  781. var maxSizes = getAdjustedSizes({
  782. aspectRatio: aspectRatio,
  783. width: maxWidth,
  784. height: maxHeight
  785. });
  786. var minSizes = getAdjustedSizes({
  787. aspectRatio: aspectRatio,
  788. width: minWidth,
  789. height: minHeight
  790. }, 'cover');
  791. var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth));
  792. var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight));
  793. // Note: should always use image's natural sizes for drawing as
  794. // imageData.naturalWidth === canvasData.naturalHeight when rotate % 180 === 90
  795. var destMaxSizes = getAdjustedSizes({
  796. aspectRatio: imageAspectRatio,
  797. width: maxWidth,
  798. height: maxHeight
  799. });
  800. var destMinSizes = getAdjustedSizes({
  801. aspectRatio: imageAspectRatio,
  802. width: minWidth,
  803. height: minHeight
  804. }, 'cover');
  805. var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth));
  806. var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight));
  807. var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight];
  808. canvas.width = normalizeDecimalNumber(width);
  809. canvas.height = normalizeDecimalNumber(height);
  810. context.fillStyle = fillColor;
  811. context.fillRect(0, 0, width, height);
  812. context.save();
  813. context.translate(width / 2, height / 2);
  814. context.rotate(rotate * Math.PI / 180);
  815. context.scale(scaleX, scaleY);
  816. context.imageSmoothingEnabled = imageSmoothingEnabled;
  817. context.imageSmoothingQuality = imageSmoothingQuality;
  818. context.drawImage.apply(context, [image].concat(toConsumableArray(params.map(function (param) {
  819. return Math.floor(normalizeDecimalNumber(param));
  820. }))));
  821. context.restore();
  822. return canvas;
  823. }
  824. var fromCharCode = String.fromCharCode;
  825. /**
  826. * Get string from char code in data view.
  827. * @param {DataView} dataView - The data view for read.
  828. * @param {number} start - The start index.
  829. * @param {number} length - The read length.
  830. * @returns {string} The read result.
  831. */
  832. function getStringFromCharCode(dataView, start, length) {
  833. var str = '';
  834. var i = void 0;
  835. length += start;
  836. for (i = start; i < length; i += 1) {
  837. str += fromCharCode(dataView.getUint8(i));
  838. }
  839. return str;
  840. }
  841. var REGEXP_DATA_URL_HEAD = /^data:.*,/;
  842. /**
  843. * Transform Data URL to array buffer.
  844. * @param {string} dataURL - The Data URL to transform.
  845. * @returns {ArrayBuffer} The result array buffer.
  846. */
  847. function dataURLToArrayBuffer(dataURL) {
  848. var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, '');
  849. var binary = atob(base64);
  850. var arrayBuffer = new ArrayBuffer(binary.length);
  851. var uint8 = new Uint8Array(arrayBuffer);
  852. forEach(uint8, function (value, i) {
  853. uint8[i] = binary.charCodeAt(i);
  854. });
  855. return arrayBuffer;
  856. }
  857. /**
  858. * Transform array buffer to Data URL.
  859. * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.
  860. * @param {string} mimeType - The mime type of the Data URL.
  861. * @returns {string} The result Data URL.
  862. */
  863. function arrayBufferToDataURL(arrayBuffer, mimeType) {
  864. var uint8 = new Uint8Array(arrayBuffer);
  865. var data = '';
  866. // TypedArray.prototype.forEach is not supported in some browsers.
  867. forEach(uint8, function (value) {
  868. data += fromCharCode(value);
  869. });
  870. return 'data:' + mimeType + ';base64,' + btoa(data);
  871. }
  872. /**
  873. * Get orientation value from given array buffer.
  874. * @param {ArrayBuffer} arrayBuffer - The array buffer to read.
  875. * @returns {number} The read orientation value.
  876. */
  877. function getOrientation(arrayBuffer) {
  878. var dataView = new DataView(arrayBuffer);
  879. var orientation = void 0;
  880. var littleEndian = void 0;
  881. var app1Start = void 0;
  882. var ifdStart = void 0;
  883. // Only handle JPEG image (start by 0xFFD8)
  884. if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {
  885. var length = dataView.byteLength;
  886. var offset = 2;
  887. while (offset < length) {
  888. if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {
  889. app1Start = offset;
  890. break;
  891. }
  892. offset += 1;
  893. }
  894. }
  895. if (app1Start) {
  896. var exifIDCode = app1Start + 4;
  897. var tiffOffset = app1Start + 10;
  898. if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {
  899. var endianness = dataView.getUint16(tiffOffset);
  900. littleEndian = endianness === 0x4949;
  901. if (littleEndian || endianness === 0x4D4D /* bigEndian */) {
  902. if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {
  903. var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
  904. if (firstIFDOffset >= 0x00000008) {
  905. ifdStart = tiffOffset + firstIFDOffset;
  906. }
  907. }
  908. }
  909. }
  910. }
  911. if (ifdStart) {
  912. var _length = dataView.getUint16(ifdStart, littleEndian);
  913. var _offset = void 0;
  914. var i = void 0;
  915. for (i = 0; i < _length; i += 1) {
  916. _offset = ifdStart + i * 12 + 2;
  917. if (dataView.getUint16(_offset, littleEndian) === 0x0112 /* Orientation */) {
  918. // 8 is the offset of the current tag's value
  919. _offset += 8;
  920. // Get the original orientation value
  921. orientation = dataView.getUint16(_offset, littleEndian);
  922. // Override the orientation with its default value
  923. dataView.setUint16(_offset, 1, littleEndian);
  924. break;
  925. }
  926. }
  927. }
  928. return orientation;
  929. }
  930. /**
  931. * Parse Exif Orientation value.
  932. * @param {number} orientation - The orientation to parse.
  933. * @returns {Object} The parsed result.
  934. */
  935. function parseOrientation(orientation) {
  936. var rotate = 0;
  937. var scaleX = 1;
  938. var scaleY = 1;
  939. switch (orientation) {
  940. // Flip horizontal
  941. case 2:
  942. scaleX = -1;
  943. break;
  944. // Rotate left 180°
  945. case 3:
  946. rotate = -180;
  947. break;
  948. // Flip vertical
  949. case 4:
  950. scaleY = -1;
  951. break;
  952. // Flip vertical and rotate right 90°
  953. case 5:
  954. rotate = 90;
  955. scaleY = -1;
  956. break;
  957. // Rotate right 90°
  958. case 6:
  959. rotate = 90;
  960. break;
  961. // Flip horizontal and rotate right 90°
  962. case 7:
  963. rotate = 90;
  964. scaleX = -1;
  965. break;
  966. // Rotate left 90°
  967. case 8:
  968. rotate = -90;
  969. break;
  970. default:
  971. }
  972. return {
  973. rotate: rotate,
  974. scaleX: scaleX,
  975. scaleY: scaleY
  976. };
  977. }
  978. var render = {
  979. render: function render() {
  980. this.initContainer();
  981. this.initCanvas();
  982. this.initCropBox();
  983. this.renderCanvas();
  984. if (this.cropped) {
  985. this.renderCropBox();
  986. }
  987. },
  988. initContainer: function initContainer() {
  989. var element = this.element,
  990. options = this.options,
  991. container = this.container,
  992. cropper = this.cropper;
  993. addClass(cropper, CLASS_HIDDEN);
  994. removeClass(element, CLASS_HIDDEN);
  995. var containerData = {
  996. width: Math.max(container.offsetWidth, Number(options.minContainerWidth) || 200),
  997. height: Math.max(container.offsetHeight, Number(options.minContainerHeight) || 100)
  998. };
  999. this.containerData = containerData;
  1000. setStyle(cropper, {
  1001. width: containerData.width,
  1002. height: containerData.height
  1003. });
  1004. addClass(element, CLASS_HIDDEN);
  1005. removeClass(cropper, CLASS_HIDDEN);
  1006. },
  1007. // Canvas (image wrapper)
  1008. initCanvas: function initCanvas() {
  1009. var containerData = this.containerData,
  1010. imageData = this.imageData;
  1011. var viewMode = this.options.viewMode;
  1012. var rotated = Math.abs(imageData.rotate) % 180 === 90;
  1013. var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth;
  1014. var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight;
  1015. var aspectRatio = naturalWidth / naturalHeight;
  1016. var canvasWidth = containerData.width;
  1017. var canvasHeight = containerData.height;
  1018. if (containerData.height * aspectRatio > containerData.width) {
  1019. if (viewMode === 3) {
  1020. canvasWidth = containerData.height * aspectRatio;
  1021. } else {
  1022. canvasHeight = containerData.width / aspectRatio;
  1023. }
  1024. } else if (viewMode === 3) {
  1025. canvasHeight = containerData.width / aspectRatio;
  1026. } else {
  1027. canvasWidth = containerData.height * aspectRatio;
  1028. }
  1029. var canvasData = {
  1030. aspectRatio: aspectRatio,
  1031. naturalWidth: naturalWidth,
  1032. naturalHeight: naturalHeight,
  1033. width: canvasWidth,
  1034. height: canvasHeight
  1035. };
  1036. canvasData.left = (containerData.width - canvasWidth) / 2;
  1037. canvasData.top = (containerData.height - canvasHeight) / 2;
  1038. canvasData.oldLeft = canvasData.left;
  1039. canvasData.oldTop = canvasData.top;
  1040. this.canvasData = canvasData;
  1041. this.limited = viewMode === 1 || viewMode === 2;
  1042. this.limitCanvas(true, true);
  1043. this.initialImageData = assign({}, imageData);
  1044. this.initialCanvasData = assign({}, canvasData);
  1045. },
  1046. limitCanvas: function limitCanvas(sizeLimited, positionLimited) {
  1047. var options = this.options,
  1048. containerData = this.containerData,
  1049. canvasData = this.canvasData,
  1050. cropBoxData = this.cropBoxData;
  1051. var viewMode = options.viewMode;
  1052. var aspectRatio = canvasData.aspectRatio;
  1053. var cropped = this.cropped && cropBoxData;
  1054. if (sizeLimited) {
  1055. var minCanvasWidth = Number(options.minCanvasWidth) || 0;
  1056. var minCanvasHeight = Number(options.minCanvasHeight) || 0;
  1057. if (viewMode > 1) {
  1058. minCanvasWidth = Math.max(minCanvasWidth, containerData.width);
  1059. minCanvasHeight = Math.max(minCanvasHeight, containerData.height);
  1060. if (viewMode === 3) {
  1061. if (minCanvasHeight * aspectRatio > minCanvasWidth) {
  1062. minCanvasWidth = minCanvasHeight * aspectRatio;
  1063. } else {
  1064. minCanvasHeight = minCanvasWidth / aspectRatio;
  1065. }
  1066. }
  1067. } else if (viewMode > 0) {
  1068. if (minCanvasWidth) {
  1069. minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0);
  1070. } else if (minCanvasHeight) {
  1071. minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0);
  1072. } else if (cropped) {
  1073. minCanvasWidth = cropBoxData.width;
  1074. minCanvasHeight = cropBoxData.height;
  1075. if (minCanvasHeight * aspectRatio > minCanvasWidth) {
  1076. minCanvasWidth = minCanvasHeight * aspectRatio;
  1077. } else {
  1078. minCanvasHeight = minCanvasWidth / aspectRatio;
  1079. }
  1080. }
  1081. }
  1082. var _getAdjustedSizes = getAdjustedSizes({
  1083. aspectRatio: aspectRatio,
  1084. width: minCanvasWidth,
  1085. height: minCanvasHeight
  1086. });
  1087. minCanvasWidth = _getAdjustedSizes.width;
  1088. minCanvasHeight = _getAdjustedSizes.height;
  1089. canvasData.minWidth = minCanvasWidth;
  1090. canvasData.minHeight = minCanvasHeight;
  1091. canvasData.maxWidth = Infinity;
  1092. canvasData.maxHeight = Infinity;
  1093. }
  1094. if (positionLimited) {
  1095. if (viewMode) {
  1096. var newCanvasLeft = containerData.width - canvasData.width;
  1097. var newCanvasTop = containerData.height - canvasData.height;
  1098. canvasData.minLeft = Math.min(0, newCanvasLeft);
  1099. canvasData.minTop = Math.min(0, newCanvasTop);
  1100. canvasData.maxLeft = Math.max(0, newCanvasLeft);
  1101. canvasData.maxTop = Math.max(0, newCanvasTop);
  1102. if (cropped && this.limited) {
  1103. canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width));
  1104. canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height));
  1105. canvasData.maxLeft = cropBoxData.left;
  1106. canvasData.maxTop = cropBoxData.top;
  1107. if (viewMode === 2) {
  1108. if (canvasData.width >= containerData.width) {
  1109. canvasData.minLeft = Math.min(0, newCanvasLeft);
  1110. canvasData.maxLeft = Math.max(0, newCanvasLeft);
  1111. }
  1112. if (canvasData.height >= containerData.height) {
  1113. canvasData.minTop = Math.min(0, newCanvasTop);
  1114. canvasData.maxTop = Math.max(0, newCanvasTop);
  1115. }
  1116. }
  1117. }
  1118. } else {
  1119. canvasData.minLeft = -canvasData.width;
  1120. canvasData.minTop = -canvasData.height;
  1121. canvasData.maxLeft = containerData.width;
  1122. canvasData.maxTop = containerData.height;
  1123. }
  1124. }
  1125. },
  1126. renderCanvas: function renderCanvas(changed, transformed) {
  1127. var canvasData = this.canvasData,
  1128. imageData = this.imageData;
  1129. if (transformed) {
  1130. var _getRotatedSizes = getRotatedSizes({
  1131. width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1),
  1132. height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1),
  1133. degree: imageData.rotate || 0
  1134. }),
  1135. naturalWidth = _getRotatedSizes.width,
  1136. naturalHeight = _getRotatedSizes.height;
  1137. var width = canvasData.width * (naturalWidth / canvasData.naturalWidth);
  1138. var height = canvasData.height * (naturalHeight / canvasData.naturalHeight);
  1139. canvasData.left -= (width - canvasData.width) / 2;
  1140. canvasData.top -= (height - canvasData.height) / 2;
  1141. canvasData.width = width;
  1142. canvasData.height = height;
  1143. canvasData.aspectRatio = naturalWidth / naturalHeight;
  1144. canvasData.naturalWidth = naturalWidth;
  1145. canvasData.naturalHeight = naturalHeight;
  1146. this.limitCanvas(true, false);
  1147. }
  1148. if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) {
  1149. canvasData.left = canvasData.oldLeft;
  1150. }
  1151. if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) {
  1152. canvasData.top = canvasData.oldTop;
  1153. }
  1154. canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth);
  1155. canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight);
  1156. this.limitCanvas(false, true);
  1157. canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft);
  1158. canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop);
  1159. canvasData.oldLeft = canvasData.left;
  1160. canvasData.oldTop = canvasData.top;
  1161. setStyle(this.canvas, assign({
  1162. width: canvasData.width,
  1163. height: canvasData.height
  1164. }, getTransforms({
  1165. translateX: canvasData.left,
  1166. translateY: canvasData.top
  1167. })));
  1168. this.renderImage(changed);
  1169. if (this.cropped && this.limited) {
  1170. this.limitCropBox(true, true);
  1171. }
  1172. },
  1173. renderImage: function renderImage(changed) {
  1174. var canvasData = this.canvasData,
  1175. imageData = this.imageData;
  1176. var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth);
  1177. var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight);
  1178. assign(imageData, {
  1179. width: width,
  1180. height: height,
  1181. left: (canvasData.width - width) / 2,
  1182. top: (canvasData.height - height) / 2
  1183. });
  1184. setStyle(this.image, assign({
  1185. width: imageData.width,
  1186. height: imageData.height
  1187. }, getTransforms(assign({
  1188. translateX: imageData.left,
  1189. translateY: imageData.top
  1190. }, imageData))));
  1191. if (changed) {
  1192. this.output();
  1193. }
  1194. },
  1195. initCropBox: function initCropBox() {
  1196. var options = this.options,
  1197. canvasData = this.canvasData;
  1198. var aspectRatio = options.aspectRatio;
  1199. var autoCropArea = Number(options.autoCropArea) || 0.8;
  1200. var cropBoxData = {
  1201. width: canvasData.width,
  1202. height: canvasData.height
  1203. };
  1204. if (aspectRatio) {
  1205. if (canvasData.height * aspectRatio > canvasData.width) {
  1206. cropBoxData.height = cropBoxData.width / aspectRatio;
  1207. } else {
  1208. cropBoxData.width = cropBoxData.height * aspectRatio;
  1209. }
  1210. }
  1211. this.cropBoxData = cropBoxData;
  1212. this.limitCropBox(true, true);
  1213. // Initialize auto crop area
  1214. cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);
  1215. cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);
  1216. // The width/height of auto crop area must large than "minWidth/Height"
  1217. cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea);
  1218. cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea);
  1219. cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2;
  1220. cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2;
  1221. cropBoxData.oldLeft = cropBoxData.left;
  1222. cropBoxData.oldTop = cropBoxData.top;
  1223. this.initialCropBoxData = assign({}, cropBoxData);
  1224. },
  1225. limitCropBox: function limitCropBox(sizeLimited, positionLimited) {
  1226. var options = this.options,
  1227. containerData = this.containerData,
  1228. canvasData = this.canvasData,
  1229. cropBoxData = this.cropBoxData,
  1230. limited = this.limited;
  1231. var aspectRatio = options.aspectRatio;
  1232. if (sizeLimited) {
  1233. var minCropBoxWidth = Number(options.minCropBoxWidth) || 0;
  1234. var minCropBoxHeight = Number(options.minCropBoxHeight) || 0;
  1235. var maxCropBoxWidth = Math.min(containerData.width, limited ? canvasData.width : containerData.width);
  1236. var maxCropBoxHeight = Math.min(containerData.height, limited ? canvasData.height : containerData.height);
  1237. // The min/maxCropBoxWidth/Height must be less than container's width/height
  1238. minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width);
  1239. minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height);
  1240. if (aspectRatio) {
  1241. if (minCropBoxWidth && minCropBoxHeight) {
  1242. if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {
  1243. minCropBoxHeight = minCropBoxWidth / aspectRatio;
  1244. } else {
  1245. minCropBoxWidth = minCropBoxHeight * aspectRatio;
  1246. }
  1247. } else if (minCropBoxWidth) {
  1248. minCropBoxHeight = minCropBoxWidth / aspectRatio;
  1249. } else if (minCropBoxHeight) {
  1250. minCropBoxWidth = minCropBoxHeight * aspectRatio;
  1251. }
  1252. if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {
  1253. maxCropBoxHeight = maxCropBoxWidth / aspectRatio;
  1254. } else {
  1255. maxCropBoxWidth = maxCropBoxHeight * aspectRatio;
  1256. }
  1257. }
  1258. // The minWidth/Height must be less than maxWidth/Height
  1259. cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth);
  1260. cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight);
  1261. cropBoxData.maxWidth = maxCropBoxWidth;
  1262. cropBoxData.maxHeight = maxCropBoxHeight;
  1263. }
  1264. if (positionLimited) {
  1265. if (limited) {
  1266. cropBoxData.minLeft = Math.max(0, canvasData.left);
  1267. cropBoxData.minTop = Math.max(0, canvasData.top);
  1268. cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width;
  1269. cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height;
  1270. } else {
  1271. cropBoxData.minLeft = 0;
  1272. cropBoxData.minTop = 0;
  1273. cropBoxData.maxLeft = containerData.width - cropBoxData.width;
  1274. cropBoxData.maxTop = containerData.height - cropBoxData.height;
  1275. }
  1276. }
  1277. },
  1278. renderCropBox: function renderCropBox() {
  1279. var options = this.options,
  1280. containerData = this.containerData,
  1281. cropBoxData = this.cropBoxData;
  1282. if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) {
  1283. cropBoxData.left = cropBoxData.oldLeft;
  1284. }
  1285. if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) {
  1286. cropBoxData.top = cropBoxData.oldTop;
  1287. }
  1288. cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);
  1289. cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);
  1290. this.limitCropBox(false, true);
  1291. cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft);
  1292. cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop);
  1293. cropBoxData.oldLeft = cropBoxData.left;
  1294. cropBoxData.oldTop = cropBoxData.top;
  1295. if (options.movable && options.cropBoxMovable) {
  1296. // Turn to move the canvas when the crop box is equal to the container
  1297. setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL);
  1298. }
  1299. setStyle(this.cropBox, assign({
  1300. width: cropBoxData.width,
  1301. height: cropBoxData.height
  1302. }, getTransforms({
  1303. translateX: cropBoxData.left,
  1304. translateY: cropBoxData.top
  1305. })));
  1306. if (this.cropped && this.limited) {
  1307. this.limitCanvas(true, true);
  1308. }
  1309. if (!this.disabled) {
  1310. this.output();
  1311. }
  1312. },
  1313. output: function output() {
  1314. this.preview();
  1315. dispatchEvent(this.element, EVENT_CROP, this.getData());
  1316. }
  1317. };
  1318. var preview = {
  1319. initPreview: function initPreview() {
  1320. var crossOrigin = this.crossOrigin;
  1321. var preview = this.options.preview;
  1322. var url = crossOrigin ? this.crossOriginUrl : this.url;
  1323. var image = document.createElement('img');
  1324. if (crossOrigin) {
  1325. image.crossOrigin = crossOrigin;
  1326. }
  1327. image.src = url;
  1328. this.viewBox.appendChild(image);
  1329. this.viewBoxImage = image;
  1330. if (!preview) {
  1331. return;
  1332. }
  1333. var previews = preview;
  1334. if (typeof preview === 'string') {
  1335. previews = this.element.ownerDocument.querySelectorAll(preview);
  1336. } else if (preview.querySelector) {
  1337. previews = [preview];
  1338. }
  1339. this.previews = previews;
  1340. forEach(previews, function (el) {
  1341. var img = document.createElement('img');
  1342. // Save the original size for recover
  1343. setData(el, DATA_PREVIEW, {
  1344. width: el.offsetWidth,
  1345. height: el.offsetHeight,
  1346. html: el.innerHTML
  1347. });
  1348. if (crossOrigin) {
  1349. img.crossOrigin = crossOrigin;
  1350. }
  1351. img.src = url;
  1352. /**
  1353. * Override img element styles
  1354. * Add `display:block` to avoid margin top issue
  1355. * Add `height:auto` to override `height` attribute on IE8
  1356. * (Occur only when margin-top <= -height)
  1357. */
  1358. img.style.cssText = 'display:block;' + 'width:100%;' + 'height:auto;' + 'min-width:0!important;' + 'min-height:0!important;' + 'max-width:none!important;' + 'max-height:none!important;' + 'image-orientation:0deg!important;"';
  1359. el.innerHTML = '';
  1360. el.appendChild(img);
  1361. });
  1362. },
  1363. resetPreview: function resetPreview() {
  1364. forEach(this.previews, function (element) {
  1365. var data = getData(element, DATA_PREVIEW);
  1366. setStyle(element, {
  1367. width: data.width,
  1368. height: data.height
  1369. });
  1370. element.innerHTML = data.html;
  1371. removeData(element, DATA_PREVIEW);
  1372. });
  1373. },
  1374. preview: function preview() {
  1375. var imageData = this.imageData,
  1376. canvasData = this.canvasData,
  1377. cropBoxData = this.cropBoxData;
  1378. var cropBoxWidth = cropBoxData.width,
  1379. cropBoxHeight = cropBoxData.height;
  1380. var width = imageData.width,
  1381. height = imageData.height;
  1382. var left = cropBoxData.left - canvasData.left - imageData.left;
  1383. var top = cropBoxData.top - canvasData.top - imageData.top;
  1384. if (!this.cropped || this.disabled) {
  1385. return;
  1386. }
  1387. setStyle(this.viewBoxImage, assign({
  1388. width: width,
  1389. height: height
  1390. }, getTransforms(assign({
  1391. translateX: -left,
  1392. translateY: -top
  1393. }, imageData))));
  1394. forEach(this.previews, function (element) {
  1395. var data = getData(element, DATA_PREVIEW);
  1396. var originalWidth = data.width;
  1397. var originalHeight = data.height;
  1398. var newWidth = originalWidth;
  1399. var newHeight = originalHeight;
  1400. var ratio = 1;
  1401. if (cropBoxWidth) {
  1402. ratio = originalWidth / cropBoxWidth;
  1403. newHeight = cropBoxHeight * ratio;
  1404. }
  1405. if (cropBoxHeight && newHeight > originalHeight) {
  1406. ratio = originalHeight / cropBoxHeight;
  1407. newWidth = cropBoxWidth * ratio;
  1408. newHeight = originalHeight;
  1409. }
  1410. setStyle(element, {
  1411. width: newWidth,
  1412. height: newHeight
  1413. });
  1414. setStyle(element.getElementsByTagName('img')[0], assign({
  1415. width: width * ratio,
  1416. height: height * ratio
  1417. }, getTransforms(assign({
  1418. translateX: -left * ratio,
  1419. translateY: -top * ratio
  1420. }, imageData))));
  1421. });
  1422. }
  1423. };
  1424. var events = {
  1425. bind: function bind() {
  1426. var element = this.element,
  1427. options = this.options,
  1428. cropper = this.cropper;
  1429. if (isFunction(options.cropstart)) {
  1430. addListener(element, EVENT_CROP_START, options.cropstart);
  1431. }
  1432. if (isFunction(options.cropmove)) {
  1433. addListener(element, EVENT_CROP_MOVE, options.cropmove);
  1434. }
  1435. if (isFunction(options.cropend)) {
  1436. addListener(element, EVENT_CROP_END, options.cropend);
  1437. }
  1438. if (isFunction(options.crop)) {
  1439. addListener(element, EVENT_CROP, options.crop);
  1440. }
  1441. if (isFunction(options.zoom)) {
  1442. addListener(element, EVENT_ZOOM, options.zoom);
  1443. }
  1444. addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this));
  1445. if (options.zoomable && options.zoomOnWheel) {
  1446. addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this));
  1447. }
  1448. if (options.toggleDragModeOnDblclick) {
  1449. addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this));
  1450. }
  1451. addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this));
  1452. addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this));
  1453. if (options.responsive) {
  1454. addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this));
  1455. }
  1456. },
  1457. unbind: function unbind() {
  1458. var element = this.element,
  1459. options = this.options,
  1460. cropper = this.cropper;
  1461. if (isFunction(options.cropstart)) {
  1462. removeListener(element, EVENT_CROP_START, options.cropstart);
  1463. }
  1464. if (isFunction(options.cropmove)) {
  1465. removeListener(element, EVENT_CROP_MOVE, options.cropmove);
  1466. }
  1467. if (isFunction(options.cropend)) {
  1468. removeListener(element, EVENT_CROP_END, options.cropend);
  1469. }
  1470. if (isFunction(options.crop)) {
  1471. removeListener(element, EVENT_CROP, options.crop);
  1472. }
  1473. if (isFunction(options.zoom)) {
  1474. removeListener(element, EVENT_ZOOM, options.zoom);
  1475. }
  1476. removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart);
  1477. if (options.zoomable && options.zoomOnWheel) {
  1478. removeListener(cropper, EVENT_WHEEL, this.onWheel);
  1479. }
  1480. if (options.toggleDragModeOnDblclick) {
  1481. removeListener(cropper, EVENT_DBLCLICK, this.onDblclick);
  1482. }
  1483. removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove);
  1484. removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd);
  1485. if (options.responsive) {
  1486. removeListener(window, EVENT_RESIZE, this.onResize);
  1487. }
  1488. }
  1489. };
  1490. var handlers = {
  1491. resize: function resize() {
  1492. var options = this.options,
  1493. container = this.container,
  1494. containerData = this.containerData;
  1495. var minContainerWidth = Number(options.minContainerWidth) || 200;
  1496. var minContainerHeight = Number(options.minContainerHeight) || 100;
  1497. if (this.disabled || containerData.width <= minContainerWidth || containerData.height <= minContainerHeight) {
  1498. return;
  1499. }
  1500. var ratio = container.offsetWidth / containerData.width;
  1501. // Resize when width changed or height changed
  1502. if (ratio !== 1 || container.offsetHeight !== containerData.height) {
  1503. var canvasData = void 0;
  1504. var cropBoxData = void 0;
  1505. if (options.restore) {
  1506. canvasData = this.getCanvasData();
  1507. cropBoxData = this.getCropBoxData();
  1508. }
  1509. this.render();
  1510. if (options.restore) {
  1511. this.setCanvasData(forEach(canvasData, function (n, i) {
  1512. canvasData[i] = n * ratio;
  1513. }));
  1514. this.setCropBoxData(forEach(cropBoxData, function (n, i) {
  1515. cropBoxData[i] = n * ratio;
  1516. }));
  1517. }
  1518. }
  1519. },
  1520. dblclick: function dblclick() {
  1521. if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) {
  1522. return;
  1523. }
  1524. this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP);
  1525. },
  1526. wheel: function wheel(e) {
  1527. var _this = this;
  1528. var ratio = Number(this.options.wheelZoomRatio) || 0.1;
  1529. var delta = 1;
  1530. if (this.disabled) {
  1531. return;
  1532. }
  1533. e.preventDefault();
  1534. // Limit wheel speed to prevent zoom too fast (#21)
  1535. if (this.wheeling) {
  1536. return;
  1537. }
  1538. this.wheeling = true;
  1539. setTimeout(function () {
  1540. _this.wheeling = false;
  1541. }, 50);
  1542. if (e.deltaY) {
  1543. delta = e.deltaY > 0 ? 1 : -1;
  1544. } else if (e.wheelDelta) {
  1545. delta = -e.wheelDelta / 120;
  1546. } else if (e.detail) {
  1547. delta = e.detail > 0 ? 1 : -1;
  1548. }
  1549. this.zoom(-delta * ratio, e);
  1550. },
  1551. cropStart: function cropStart(e) {
  1552. if (this.disabled) {
  1553. return;
  1554. }
  1555. var options = this.options,
  1556. pointers = this.pointers;
  1557. var action = void 0;
  1558. if (e.changedTouches) {
  1559. // Handle touch event
  1560. forEach(e.changedTouches, function (touch) {
  1561. pointers[touch.identifier] = getPointer(touch);
  1562. });
  1563. } else {
  1564. // Handle mouse event and pointer event
  1565. pointers[e.pointerId || 0] = getPointer(e);
  1566. }
  1567. if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) {
  1568. action = ACTION_ZOOM;
  1569. } else {
  1570. action = getData(e.target, DATA_ACTION);
  1571. }
  1572. if (!REGEXP_ACTIONS.test(action)) {
  1573. return;
  1574. }
  1575. if (dispatchEvent(this.element, EVENT_CROP_START, {
  1576. originalEvent: e,
  1577. action: action
  1578. }) === false) {
  1579. return;
  1580. }
  1581. e.preventDefault();
  1582. this.action = action;
  1583. this.cropping = false;
  1584. if (action === ACTION_CROP) {
  1585. this.cropping = true;
  1586. addClass(this.dragBox, CLASS_MODAL);
  1587. }
  1588. },
  1589. cropMove: function cropMove(e) {
  1590. var action = this.action;
  1591. if (this.disabled || !action) {
  1592. return;
  1593. }
  1594. var pointers = this.pointers;
  1595. e.preventDefault();
  1596. if (dispatchEvent(this.element, EVENT_CROP_MOVE, {
  1597. originalEvent: e,
  1598. action: action
  1599. }) === false) {
  1600. return;
  1601. }
  1602. if (e.changedTouches) {
  1603. forEach(e.changedTouches, function (touch) {
  1604. assign(pointers[touch.identifier], getPointer(touch, true));
  1605. });
  1606. } else {
  1607. assign(pointers[e.pointerId || 0], getPointer(e, true));
  1608. }
  1609. this.change(e);
  1610. },
  1611. cropEnd: function cropEnd(e) {
  1612. if (this.disabled) {
  1613. return;
  1614. }
  1615. var action = this.action,
  1616. pointers = this.pointers;
  1617. if (e.changedTouches) {
  1618. forEach(e.changedTouches, function (touch) {
  1619. delete pointers[touch.identifier];
  1620. });
  1621. } else {
  1622. delete pointers[e.pointerId || 0];
  1623. }
  1624. if (!action) {
  1625. return;
  1626. }
  1627. e.preventDefault();
  1628. if (!Object.keys(pointers).length) {
  1629. this.action = '';
  1630. }
  1631. if (this.cropping) {
  1632. this.cropping = false;
  1633. toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal);
  1634. }
  1635. dispatchEvent(this.element, EVENT_CROP_END, {
  1636. originalEvent: e,
  1637. action: action
  1638. });
  1639. }
  1640. };
  1641. var change = {
  1642. change: function change(e) {
  1643. var options = this.options,
  1644. canvasData = this.canvasData,
  1645. containerData = this.containerData,
  1646. cropBoxData = this.cropBoxData,
  1647. pointers = this.pointers;
  1648. var action = this.action;
  1649. var aspectRatio = options.aspectRatio;
  1650. var left = cropBoxData.left,
  1651. top = cropBoxData.top,
  1652. width = cropBoxData.width,
  1653. height = cropBoxData.height;
  1654. var right = left + width;
  1655. var bottom = top + height;
  1656. var minLeft = 0;
  1657. var minTop = 0;
  1658. var maxWidth = containerData.width;
  1659. var maxHeight = containerData.height;
  1660. var renderable = true;
  1661. var offset = void 0;
  1662. // Locking aspect ratio in "free mode" by holding shift key
  1663. if (!aspectRatio && e.shiftKey) {
  1664. aspectRatio = width && height ? width / height : 1;
  1665. }
  1666. if (this.limited) {
  1667. minLeft = cropBoxData.minLeft;
  1668. minTop = cropBoxData.minTop;
  1669. maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width);
  1670. maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height);
  1671. }
  1672. var pointer = pointers[Object.keys(pointers)[0]];
  1673. var range = {
  1674. x: pointer.endX - pointer.startX,
  1675. y: pointer.endY - pointer.startY
  1676. };
  1677. var check = function check(side) {
  1678. switch (side) {
  1679. case ACTION_EAST:
  1680. if (right + range.x > maxWidth) {
  1681. range.x = maxWidth - right;
  1682. }
  1683. break;
  1684. case ACTION_WEST:
  1685. if (left + range.x < minLeft) {
  1686. range.x = minLeft - left;
  1687. }
  1688. break;
  1689. case ACTION_NORTH:
  1690. if (top + range.y < minTop) {
  1691. range.y = minTop - top;
  1692. }
  1693. break;
  1694. case ACTION_SOUTH:
  1695. if (bottom + range.y > maxHeight) {
  1696. range.y = maxHeight - bottom;
  1697. }
  1698. break;
  1699. default:
  1700. }
  1701. };
  1702. switch (action) {
  1703. // Move crop box
  1704. case ACTION_ALL:
  1705. left += range.x;
  1706. top += range.y;
  1707. break;
  1708. // Resize crop box
  1709. case ACTION_EAST:
  1710. if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) {
  1711. renderable = false;
  1712. break;
  1713. }
  1714. check(ACTION_EAST);
  1715. width += range.x;
  1716. if (aspectRatio) {
  1717. height = width / aspectRatio;
  1718. top -= range.x / aspectRatio / 2;
  1719. }
  1720. if (width < 0) {
  1721. action = ACTION_WEST;
  1722. width = 0;
  1723. }
  1724. break;
  1725. case ACTION_NORTH:
  1726. if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) {
  1727. renderable = false;
  1728. break;
  1729. }
  1730. check(ACTION_NORTH);
  1731. height -= range.y;
  1732. top += range.y;
  1733. if (aspectRatio) {
  1734. width = height * aspectRatio;
  1735. left += range.y * aspectRatio / 2;
  1736. }
  1737. if (height < 0) {
  1738. action = ACTION_SOUTH;
  1739. height = 0;
  1740. }
  1741. break;
  1742. case ACTION_WEST:
  1743. if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) {
  1744. renderable = false;
  1745. break;
  1746. }
  1747. check(ACTION_WEST);
  1748. width -= range.x;
  1749. left += range.x;
  1750. if (aspectRatio) {
  1751. height = width / aspectRatio;
  1752. top += range.x / aspectRatio / 2;
  1753. }
  1754. if (width < 0) {
  1755. action = ACTION_EAST;
  1756. width = 0;
  1757. }
  1758. break;
  1759. case ACTION_SOUTH:
  1760. if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) {
  1761. renderable = false;
  1762. break;
  1763. }
  1764. check(ACTION_SOUTH);
  1765. height += range.y;
  1766. if (aspectRatio) {
  1767. width = height * aspectRatio;
  1768. left -= range.y * aspectRatio / 2;
  1769. }
  1770. if (height < 0) {
  1771. action = ACTION_NORTH;
  1772. height = 0;
  1773. }
  1774. break;
  1775. case ACTION_NORTH_EAST:
  1776. if (aspectRatio) {
  1777. if (range.y <= 0 && (top <= minTop || right >= maxWidth)) {
  1778. renderable = false;
  1779. break;
  1780. }
  1781. check(ACTION_NORTH);
  1782. height -= range.y;
  1783. top += range.y;
  1784. width = height * aspectRatio;
  1785. } else {
  1786. check(ACTION_NORTH);
  1787. check(ACTION_EAST);
  1788. if (range.x >= 0) {
  1789. if (right < maxWidth) {
  1790. width += range.x;
  1791. } else if (range.y <= 0 && top <= minTop) {
  1792. renderable = false;
  1793. }
  1794. } else {
  1795. width += range.x;
  1796. }
  1797. if (range.y <= 0) {
  1798. if (top > minTop) {
  1799. height -= range.y;
  1800. top += range.y;
  1801. }
  1802. } else {
  1803. height -= range.y;
  1804. top += range.y;
  1805. }
  1806. }
  1807. if (width < 0 && height < 0) {
  1808. action = ACTION_SOUTH_WEST;
  1809. height = 0;
  1810. width = 0;
  1811. } else if (width < 0) {
  1812. action = ACTION_NORTH_WEST;
  1813. width = 0;
  1814. } else if (height < 0) {
  1815. action = ACTION_SOUTH_EAST;
  1816. height = 0;
  1817. }
  1818. break;
  1819. case ACTION_NORTH_WEST:
  1820. if (aspectRatio) {
  1821. if (range.y <= 0 && (top <= minTop || left <= minLeft)) {
  1822. renderable = false;
  1823. break;
  1824. }
  1825. check(ACTION_NORTH);
  1826. height -= range.y;
  1827. top += range.y;
  1828. width = height * aspectRatio;
  1829. left += range.y * aspectRatio;
  1830. } else {
  1831. check(ACTION_NORTH);
  1832. check(ACTION_WEST);
  1833. if (range.x <= 0) {
  1834. if (left > minLeft) {
  1835. width -= range.x;
  1836. left += range.x;
  1837. } else if (range.y <= 0 && top <= minTop) {
  1838. renderable = false;
  1839. }
  1840. } else {
  1841. width -= range.x;
  1842. left += range.x;
  1843. }
  1844. if (range.y <= 0) {
  1845. if (top > minTop) {
  1846. height -= range.y;
  1847. top += range.y;
  1848. }
  1849. } else {
  1850. height -= range.y;
  1851. top += range.y;
  1852. }
  1853. }
  1854. if (width < 0 && height < 0) {
  1855. action = ACTION_SOUTH_EAST;
  1856. height = 0;
  1857. width = 0;
  1858. } else if (width < 0) {
  1859. action = ACTION_NORTH_EAST;
  1860. width = 0;
  1861. } else if (height < 0) {
  1862. action = ACTION_SOUTH_WEST;
  1863. height = 0;
  1864. }
  1865. break;
  1866. case ACTION_SOUTH_WEST:
  1867. if (aspectRatio) {
  1868. if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) {
  1869. renderable = false;
  1870. break;
  1871. }
  1872. check(ACTION_WEST);
  1873. width -= range.x;
  1874. left += range.x;
  1875. height = width / aspectRatio;
  1876. } else {
  1877. check(ACTION_SOUTH);
  1878. check(ACTION_WEST);
  1879. if (range.x <= 0) {
  1880. if (left > minLeft) {
  1881. width -= range.x;
  1882. left += range.x;
  1883. } else if (range.y >= 0 && bottom >= maxHeight) {
  1884. renderable = false;
  1885. }
  1886. } else {
  1887. width -= range.x;
  1888. left += range.x;
  1889. }
  1890. if (range.y >= 0) {
  1891. if (bottom < maxHeight) {
  1892. height += range.y;
  1893. }
  1894. } else {
  1895. height += range.y;
  1896. }
  1897. }
  1898. if (width < 0 && height < 0) {
  1899. action = ACTION_NORTH_EAST;
  1900. height = 0;
  1901. width = 0;
  1902. } else if (width < 0) {
  1903. action = ACTION_SOUTH_EAST;
  1904. width = 0;
  1905. } else if (height < 0) {
  1906. action = ACTION_NORTH_WEST;
  1907. height = 0;
  1908. }
  1909. break;
  1910. case ACTION_SOUTH_EAST:
  1911. if (aspectRatio) {
  1912. if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) {
  1913. renderable = false;
  1914. break;
  1915. }
  1916. check(ACTION_EAST);
  1917. width += range.x;
  1918. height = width / aspectRatio;
  1919. } else {
  1920. check(ACTION_SOUTH);
  1921. check(ACTION_EAST);
  1922. if (range.x >= 0) {
  1923. if (right < maxWidth) {
  1924. width += range.x;
  1925. } else if (range.y >= 0 && bottom >= maxHeight) {
  1926. renderable = false;
  1927. }
  1928. } else {
  1929. width += range.x;
  1930. }
  1931. if (range.y >= 0) {
  1932. if (bottom < maxHeight) {
  1933. height += range.y;
  1934. }
  1935. } else {
  1936. height += range.y;
  1937. }
  1938. }
  1939. if (width < 0 && height < 0) {
  1940. action = ACTION_NORTH_WEST;
  1941. height = 0;
  1942. width = 0;
  1943. } else if (width < 0) {
  1944. action = ACTION_SOUTH_WEST;
  1945. width = 0;
  1946. } else if (height < 0) {
  1947. action = ACTION_NORTH_EAST;
  1948. height = 0;
  1949. }
  1950. break;
  1951. // Move canvas
  1952. case ACTION_MOVE:
  1953. this.move(range.x, range.y);
  1954. renderable = false;
  1955. break;
  1956. // Zoom canvas
  1957. case ACTION_ZOOM:
  1958. this.zoom(getMaxZoomRatio(pointers), e);
  1959. renderable = false;
  1960. break;
  1961. // Create crop box
  1962. case ACTION_CROP:
  1963. if (!range.x || !range.y) {
  1964. renderable = false;
  1965. break;
  1966. }
  1967. offset = getOffset(this.cropper);
  1968. left = pointer.startX - offset.left;
  1969. top = pointer.startY - offset.top;
  1970. width = cropBoxData.minWidth;
  1971. height = cropBoxData.minHeight;
  1972. if (range.x > 0) {
  1973. action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST;
  1974. } else if (range.x < 0) {
  1975. left -= width;
  1976. action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST;
  1977. }
  1978. if (range.y < 0) {
  1979. top -= height;
  1980. }
  1981. // Show the crop box if is hidden
  1982. if (!this.cropped) {
  1983. removeClass(this.cropBox, CLASS_HIDDEN);
  1984. this.cropped = true;
  1985. if (this.limited) {
  1986. this.limitCropBox(true, true);
  1987. }
  1988. }
  1989. break;
  1990. default:
  1991. }
  1992. if (renderable) {
  1993. cropBoxData.width = width;
  1994. cropBoxData.height = height;
  1995. cropBoxData.left = left;
  1996. cropBoxData.top = top;
  1997. this.action = action;
  1998. this.renderCropBox();
  1999. }
  2000. // Override
  2001. forEach(pointers, function (p) {
  2002. p.startX = p.endX;
  2003. p.startY = p.endY;
  2004. });
  2005. }
  2006. };
  2007. var methods = {
  2008. // Show the crop box manually
  2009. crop: function crop() {
  2010. if (this.ready && !this.cropped && !this.disabled) {
  2011. this.cropped = true;
  2012. this.limitCropBox(true, true);
  2013. if (this.options.modal) {
  2014. addClass(this.dragBox, CLASS_MODAL);
  2015. }
  2016. removeClass(this.cropBox, CLASS_HIDDEN);
  2017. this.setCropBoxData(this.initialCropBoxData);
  2018. }
  2019. return this;
  2020. },
  2021. // Reset the image and crop box to their initial states
  2022. reset: function reset() {
  2023. if (this.ready && !this.disabled) {
  2024. this.imageData = assign({}, this.initialImageData);
  2025. this.canvasData = assign({}, this.initialCanvasData);
  2026. this.cropBoxData = assign({}, this.initialCropBoxData);
  2027. this.renderCanvas();
  2028. if (this.cropped) {
  2029. this.renderCropBox();
  2030. }
  2031. }
  2032. return this;
  2033. },
  2034. // Clear the crop box
  2035. clear: function clear() {
  2036. if (this.cropped && !this.disabled) {
  2037. assign(this.cropBoxData, {
  2038. left: 0,
  2039. top: 0,
  2040. width: 0,
  2041. height: 0
  2042. });
  2043. this.cropped = false;
  2044. this.renderCropBox();
  2045. this.limitCanvas(true, true);
  2046. // Render canvas after crop box rendered
  2047. this.renderCanvas();
  2048. removeClass(this.dragBox, CLASS_MODAL);
  2049. addClass(this.cropBox, CLASS_HIDDEN);
  2050. }
  2051. return this;
  2052. },
  2053. /**
  2054. * Replace the image's src and rebuild the cropper
  2055. * @param {string} url - The new URL.
  2056. * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one.
  2057. * @returns {Cropper} this
  2058. */
  2059. replace: function replace(url) {
  2060. var hasSameSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  2061. if (!this.disabled && url) {
  2062. if (this.isImg) {
  2063. this.element.src = url;
  2064. }
  2065. if (hasSameSize) {
  2066. this.url = url;
  2067. this.image.src = url;
  2068. if (this.ready) {
  2069. this.viewBoxImage.src = url;
  2070. forEach(this.previews, function (element) {
  2071. element.getElementsByTagName('img')[0].src = url;
  2072. });
  2073. }
  2074. } else {
  2075. if (this.isImg) {
  2076. this.replaced = true;
  2077. }
  2078. this.options.data = null;
  2079. this.uncreate();
  2080. this.load(url);
  2081. }
  2082. }
  2083. return this;
  2084. },
  2085. // Enable (unfreeze) the cropper
  2086. enable: function enable() {
  2087. if (this.ready && this.disabled) {
  2088. this.disabled = false;
  2089. removeClass(this.cropper, CLASS_DISABLED);
  2090. }
  2091. return this;
  2092. },
  2093. // Disable (freeze) the cropper
  2094. disable: function disable() {
  2095. if (this.ready && !this.disabled) {
  2096. this.disabled = true;
  2097. addClass(this.cropper, CLASS_DISABLED);
  2098. }
  2099. return this;
  2100. },
  2101. /**
  2102. * Destroy the cropper and remove the instance from the image
  2103. * @returns {Cropper} this
  2104. */
  2105. destroy: function destroy() {
  2106. var element = this.element;
  2107. if (!getData(element, NAMESPACE)) {
  2108. return this;
  2109. }
  2110. if (this.isImg && this.replaced) {
  2111. element.src = this.originalUrl;
  2112. }
  2113. this.uncreate();
  2114. removeData(element, NAMESPACE);
  2115. return this;
  2116. },
  2117. /**
  2118. * Move the canvas with relative offsets
  2119. * @param {number} offsetX - The relative offset distance on the x-axis.
  2120. * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis.
  2121. * @returns {Cropper} this
  2122. */
  2123. move: function move(offsetX) {
  2124. var offsetY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : offsetX;
  2125. var _canvasData = this.canvasData,
  2126. left = _canvasData.left,
  2127. top = _canvasData.top;
  2128. return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY));
  2129. },
  2130. /**
  2131. * Move the canvas to an absolute point
  2132. * @param {number} x - The x-axis coordinate.
  2133. * @param {number} [y=x] - The y-axis coordinate.
  2134. * @returns {Cropper} this
  2135. */
  2136. moveTo: function moveTo(x) {
  2137. var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;
  2138. var canvasData = this.canvasData;
  2139. var changed = false;
  2140. x = Number(x);
  2141. y = Number(y);
  2142. if (this.ready && !this.disabled && this.options.movable) {
  2143. if (isNumber(x)) {
  2144. canvasData.left = x;
  2145. changed = true;
  2146. }
  2147. if (isNumber(y)) {
  2148. canvasData.top = y;
  2149. changed = true;
  2150. }
  2151. if (changed) {
  2152. this.renderCanvas(true);
  2153. }
  2154. }
  2155. return this;
  2156. },
  2157. /**
  2158. * Zoom the canvas with a relative ratio
  2159. * @param {number} ratio - The target ratio.
  2160. * @param {Event} _originalEvent - The original event if any.
  2161. * @returns {Cropper} this
  2162. */
  2163. zoom: function zoom(ratio, _originalEvent) {
  2164. var canvasData = this.canvasData;
  2165. ratio = Number(ratio);
  2166. if (ratio < 0) {
  2167. ratio = 1 / (1 - ratio);
  2168. } else {
  2169. ratio = 1 + ratio;
  2170. }
  2171. return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent);
  2172. },
  2173. /**
  2174. * Zoom the canvas to an absolute ratio
  2175. * @param {number} ratio - The target ratio.
  2176. * @param {Object} pivot - The zoom pivot point coordinate.
  2177. * @param {Event} _originalEvent - The original event if any.
  2178. * @returns {Cropper} this
  2179. */
  2180. zoomTo: function zoomTo(ratio, pivot, _originalEvent) {
  2181. var options = this.options,
  2182. canvasData = this.canvasData;
  2183. var width = canvasData.width,
  2184. height = canvasData.height,
  2185. naturalWidth = canvasData.naturalWidth,
  2186. naturalHeight = canvasData.naturalHeight;
  2187. ratio = Number(ratio);
  2188. if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) {
  2189. var newWidth = naturalWidth * ratio;
  2190. var newHeight = naturalHeight * ratio;
  2191. if (dispatchEvent(this.element, EVENT_ZOOM, {
  2192. originalEvent: _originalEvent,
  2193. oldRatio: width / naturalWidth,
  2194. ratio: newWidth / naturalWidth
  2195. }) === false) {
  2196. return this;
  2197. }
  2198. if (_originalEvent) {
  2199. var pointers = this.pointers;
  2200. var offset = getOffset(this.cropper);
  2201. var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : {
  2202. pageX: _originalEvent.pageX,
  2203. pageY: _originalEvent.pageY
  2204. };
  2205. // Zoom from the triggering point of the event
  2206. canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width);
  2207. canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height);
  2208. } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) {
  2209. canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width);
  2210. canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height);
  2211. } else {
  2212. // Zoom from the center of the canvas
  2213. canvasData.left -= (newWidth - width) / 2;
  2214. canvasData.top -= (newHeight - height) / 2;
  2215. }
  2216. canvasData.width = newWidth;
  2217. canvasData.height = newHeight;
  2218. this.renderCanvas(true);
  2219. }
  2220. return this;
  2221. },
  2222. /**
  2223. * Rotate the canvas with a relative degree
  2224. * @param {number} degree - The rotate degree.
  2225. * @returns {Cropper} this
  2226. */
  2227. rotate: function rotate(degree) {
  2228. return this.rotateTo((this.imageData.rotate || 0) + Number(degree));
  2229. },
  2230. /**
  2231. * Rotate the canvas to an absolute degree
  2232. * @param {number} degree - The rotate degree.
  2233. * @returns {Cropper} this
  2234. */
  2235. rotateTo: function rotateTo(degree) {
  2236. degree = Number(degree);
  2237. if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) {
  2238. this.imageData.rotate = degree % 360;
  2239. this.renderCanvas(true, true);
  2240. }
  2241. return this;
  2242. },
  2243. /**
  2244. * Scale the image on the x-axis.
  2245. * @param {number} scaleX - The scale ratio on the x-axis.
  2246. * @returns {Cropper} this
  2247. */
  2248. scaleX: function scaleX(_scaleX) {
  2249. var scaleY = this.imageData.scaleY;
  2250. return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1);
  2251. },
  2252. /**
  2253. * Scale the image on the y-axis.
  2254. * @param {number} scaleY - The scale ratio on the y-axis.
  2255. * @returns {Cropper} this
  2256. */
  2257. scaleY: function scaleY(_scaleY) {
  2258. var scaleX = this.imageData.scaleX;
  2259. return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY);
  2260. },
  2261. /**
  2262. * Scale the image
  2263. * @param {number} scaleX - The scale ratio on the x-axis.
  2264. * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis.
  2265. * @returns {Cropper} this
  2266. */
  2267. scale: function scale(scaleX) {
  2268. var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX;
  2269. var imageData = this.imageData;
  2270. var transformed = false;
  2271. scaleX = Number(scaleX);
  2272. scaleY = Number(scaleY);
  2273. if (this.ready && !this.disabled && this.options.scalable) {
  2274. if (isNumber(scaleX)) {
  2275. imageData.scaleX = scaleX;
  2276. transformed = true;
  2277. }
  2278. if (isNumber(scaleY)) {
  2279. imageData.scaleY = scaleY;
  2280. transformed = true;
  2281. }
  2282. if (transformed) {
  2283. this.renderCanvas(true, true);
  2284. }
  2285. }
  2286. return this;
  2287. },
  2288. /**
  2289. * Get the cropped area position and size data (base on the original image)
  2290. * @param {boolean} [rounded=false] - Indicate if round the data values or not.
  2291. * @returns {Object} The result cropped data.
  2292. */
  2293. getData: function getData$$1() {
  2294. var rounded = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  2295. var options = this.options,
  2296. imageData = this.imageData,
  2297. canvasData = this.canvasData,
  2298. cropBoxData = this.cropBoxData;
  2299. var data = void 0;
  2300. if (this.ready && this.cropped) {
  2301. data = {
  2302. x: cropBoxData.left - canvasData.left,
  2303. y: cropBoxData.top - canvasData.top,
  2304. width: cropBoxData.width,
  2305. height: cropBoxData.height
  2306. };
  2307. var ratio = imageData.width / imageData.naturalWidth;
  2308. forEach(data, function (n, i) {
  2309. n /= ratio;
  2310. data[i] = rounded ? Math.round(n) : n;
  2311. });
  2312. } else {
  2313. data = {
  2314. x: 0,
  2315. y: 0,
  2316. width: 0,
  2317. height: 0
  2318. };
  2319. }
  2320. if (options.rotatable) {
  2321. data.rotate = imageData.rotate || 0;
  2322. }
  2323. if (options.scalable) {
  2324. data.scaleX = imageData.scaleX || 1;
  2325. data.scaleY = imageData.scaleY || 1;
  2326. }
  2327. return data;
  2328. },
  2329. /**
  2330. * Set the cropped area position and size with new data
  2331. * @param {Object} data - The new data.
  2332. * @returns {Cropper} this
  2333. */
  2334. setData: function setData$$1(data) {
  2335. var options = this.options,
  2336. imageData = this.imageData,
  2337. canvasData = this.canvasData;
  2338. var cropBoxData = {};
  2339. if (this.ready && !this.disabled && isPlainObject(data)) {
  2340. var transformed = false;
  2341. if (options.rotatable) {
  2342. if (isNumber(data.rotate) && data.rotate !== imageData.rotate) {
  2343. imageData.rotate = data.rotate;
  2344. transformed = true;
  2345. }
  2346. }
  2347. if (options.scalable) {
  2348. if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) {
  2349. imageData.scaleX = data.scaleX;
  2350. transformed = true;
  2351. }
  2352. if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) {
  2353. imageData.scaleY = data.scaleY;
  2354. transformed = true;
  2355. }
  2356. }
  2357. if (transformed) {
  2358. this.renderCanvas(true, true);
  2359. }
  2360. var ratio = imageData.width / imageData.naturalWidth;
  2361. if (isNumber(data.x)) {
  2362. cropBoxData.left = data.x * ratio + canvasData.left;
  2363. }
  2364. if (isNumber(data.y)) {
  2365. cropBoxData.top = data.y * ratio + canvasData.top;
  2366. }
  2367. if (isNumber(data.width)) {
  2368. cropBoxData.width = data.width * ratio;
  2369. }
  2370. if (isNumber(data.height)) {
  2371. cropBoxData.height = data.height * ratio;
  2372. }
  2373. this.setCropBoxData(cropBoxData);
  2374. }
  2375. return this;
  2376. },
  2377. /**
  2378. * Get the container size data.
  2379. * @returns {Object} The result container data.
  2380. */
  2381. getContainerData: function getContainerData() {
  2382. return this.ready ? assign({}, this.containerData) : {};
  2383. },
  2384. /**
  2385. * Get the image position and size data.
  2386. * @returns {Object} The result image data.
  2387. */
  2388. getImageData: function getImageData() {
  2389. return this.sized ? assign({}, this.imageData) : {};
  2390. },
  2391. /**
  2392. * Get the canvas position and size data.
  2393. * @returns {Object} The result canvas data.
  2394. */
  2395. getCanvasData: function getCanvasData() {
  2396. var canvasData = this.canvasData;
  2397. var data = {};
  2398. if (this.ready) {
  2399. forEach(['left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight'], function (n) {
  2400. data[n] = canvasData[n];
  2401. });
  2402. }
  2403. return data;
  2404. },
  2405. /**
  2406. * Set the canvas position and size with new data.
  2407. * @param {Object} data - The new canvas data.
  2408. * @returns {Cropper} this
  2409. */
  2410. setCanvasData: function setCanvasData(data) {
  2411. var canvasData = this.canvasData;
  2412. var aspectRatio = canvasData.aspectRatio;
  2413. if (this.ready && !this.disabled && isPlainObject(data)) {
  2414. if (isNumber(data.left)) {
  2415. canvasData.left = data.left;
  2416. }
  2417. if (isNumber(data.top)) {
  2418. canvasData.top = data.top;
  2419. }
  2420. if (isNumber(data.width)) {
  2421. canvasData.width = data.width;
  2422. canvasData.height = data.width / aspectRatio;
  2423. } else if (isNumber(data.height)) {
  2424. canvasData.height = data.height;
  2425. canvasData.width = data.height * aspectRatio;
  2426. }
  2427. this.renderCanvas(true);
  2428. }
  2429. return this;
  2430. },
  2431. /**
  2432. * Get the crop box position and size data.
  2433. * @returns {Object} The result crop box data.
  2434. */
  2435. getCropBoxData: function getCropBoxData() {
  2436. var cropBoxData = this.cropBoxData;
  2437. var data = void 0;
  2438. if (this.ready && this.cropped) {
  2439. data = {
  2440. left: cropBoxData.left,
  2441. top: cropBoxData.top,
  2442. width: cropBoxData.width,
  2443. height: cropBoxData.height
  2444. };
  2445. }
  2446. return data || {};
  2447. },
  2448. /**
  2449. * Set the crop box position and size with new data.
  2450. * @param {Object} data - The new crop box data.
  2451. * @returns {Cropper} this
  2452. */
  2453. setCropBoxData: function setCropBoxData(data) {
  2454. var cropBoxData = this.cropBoxData;
  2455. var aspectRatio = this.options.aspectRatio;
  2456. var widthChanged = void 0;
  2457. var heightChanged = void 0;
  2458. if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) {
  2459. if (isNumber(data.left)) {
  2460. cropBoxData.left = data.left;
  2461. }
  2462. if (isNumber(data.top)) {
  2463. cropBoxData.top = data.top;
  2464. }
  2465. if (isNumber(data.width) && data.width !== cropBoxData.width) {
  2466. widthChanged = true;
  2467. cropBoxData.width = data.width;
  2468. }
  2469. if (isNumber(data.height) && data.height !== cropBoxData.height) {
  2470. heightChanged = true;
  2471. cropBoxData.height = data.height;
  2472. }
  2473. if (aspectRatio) {
  2474. if (widthChanged) {
  2475. cropBoxData.height = cropBoxData.width / aspectRatio;
  2476. } else if (heightChanged) {
  2477. cropBoxData.width = cropBoxData.height * aspectRatio;
  2478. }
  2479. }
  2480. this.renderCropBox();
  2481. }
  2482. return this;
  2483. },
  2484. /**
  2485. * Get a canvas drawn the cropped image.
  2486. * @param {Object} [options={}] - The config options.
  2487. * @returns {HTMLCanvasElement} - The result canvas.
  2488. */
  2489. getCroppedCanvas: function getCroppedCanvas() {
  2490. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  2491. if (!this.ready || !window.HTMLCanvasElement) {
  2492. return null;
  2493. }
  2494. var canvasData = this.canvasData;
  2495. var source = getSourceCanvas(this.image, this.imageData, canvasData, options);
  2496. // Returns the source canvas if it is not cropped.
  2497. if (!this.cropped) {
  2498. return source;
  2499. }
  2500. var _getData = this.getData(),
  2501. initialX = _getData.x,
  2502. initialY = _getData.y,
  2503. initialWidth = _getData.width,
  2504. initialHeight = _getData.height;
  2505. var ratio = source.width / Math.floor(canvasData.naturalWidth);
  2506. if (ratio !== 1) {
  2507. initialX *= ratio;
  2508. initialY *= ratio;
  2509. initialWidth *= ratio;
  2510. initialHeight *= ratio;
  2511. }
  2512. var aspectRatio = initialWidth / initialHeight;
  2513. var maxSizes = getAdjustedSizes({
  2514. aspectRatio: aspectRatio,
  2515. width: options.maxWidth || Infinity,
  2516. height: options.maxHeight || Infinity
  2517. });
  2518. var minSizes = getAdjustedSizes({
  2519. aspectRatio: aspectRatio,
  2520. width: options.minWidth || 0,
  2521. height: options.minHeight || 0
  2522. }, 'cover');
  2523. var _getAdjustedSizes = getAdjustedSizes({
  2524. aspectRatio: aspectRatio,
  2525. width: options.width || (ratio !== 1 ? source.width : initialWidth),
  2526. height: options.height || (ratio !== 1 ? source.height : initialHeight)
  2527. }),
  2528. width = _getAdjustedSizes.width,
  2529. height = _getAdjustedSizes.height;
  2530. width = Math.min(maxSizes.width, Math.max(minSizes.width, width));
  2531. height = Math.min(maxSizes.height, Math.max(minSizes.height, height));
  2532. var canvas = document.createElement('canvas');
  2533. var context = canvas.getContext('2d');
  2534. canvas.width = normalizeDecimalNumber(width);
  2535. canvas.height = normalizeDecimalNumber(height);
  2536. context.fillStyle = options.fillColor || 'transparent';
  2537. context.fillRect(0, 0, width, height);
  2538. var _options$imageSmoothi = options.imageSmoothingEnabled,
  2539. imageSmoothingEnabled = _options$imageSmoothi === undefined ? true : _options$imageSmoothi,
  2540. imageSmoothingQuality = options.imageSmoothingQuality;
  2541. context.imageSmoothingEnabled = imageSmoothingEnabled;
  2542. if (imageSmoothingQuality) {
  2543. context.imageSmoothingQuality = imageSmoothingQuality;
  2544. }
  2545. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage
  2546. var sourceWidth = source.width;
  2547. var sourceHeight = source.height;
  2548. // Source canvas parameters
  2549. var srcX = initialX;
  2550. var srcY = initialY;
  2551. var srcWidth = void 0;
  2552. var srcHeight = void 0;
  2553. // Destination canvas parameters
  2554. var dstX = void 0;
  2555. var dstY = void 0;
  2556. var dstWidth = void 0;
  2557. var dstHeight = void 0;
  2558. if (srcX <= -initialWidth || srcX > sourceWidth) {
  2559. srcX = 0;
  2560. srcWidth = 0;
  2561. dstX = 0;
  2562. dstWidth = 0;
  2563. } else if (srcX <= 0) {
  2564. dstX = -srcX;
  2565. srcX = 0;
  2566. srcWidth = Math.min(sourceWidth, initialWidth + srcX);
  2567. dstWidth = srcWidth;
  2568. } else if (srcX <= sourceWidth) {
  2569. dstX = 0;
  2570. srcWidth = Math.min(initialWidth, sourceWidth - srcX);
  2571. dstWidth = srcWidth;
  2572. }
  2573. if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) {
  2574. srcY = 0;
  2575. srcHeight = 0;
  2576. dstY = 0;
  2577. dstHeight = 0;
  2578. } else if (srcY <= 0) {
  2579. dstY = -srcY;
  2580. srcY = 0;
  2581. srcHeight = Math.min(sourceHeight, initialHeight + srcY);
  2582. dstHeight = srcHeight;
  2583. } else if (srcY <= sourceHeight) {
  2584. dstY = 0;
  2585. srcHeight = Math.min(initialHeight, sourceHeight - srcY);
  2586. dstHeight = srcHeight;
  2587. }
  2588. var params = [srcX, srcY, srcWidth, srcHeight];
  2589. // Avoid "IndexSizeError"
  2590. if (dstWidth > 0 && dstHeight > 0) {
  2591. var scale = width / initialWidth;
  2592. params.push(dstX * scale, dstY * scale, dstWidth * scale, dstHeight * scale);
  2593. }
  2594. // All the numerical parameters should be integer for `drawImage`
  2595. // https://github.com/fengyuanchen/cropper/issues/476
  2596. context.drawImage.apply(context, [source].concat(toConsumableArray(params.map(function (param) {
  2597. return Math.floor(normalizeDecimalNumber(param));
  2598. }))));
  2599. return canvas;
  2600. },
  2601. /**
  2602. * Change the aspect ratio of the crop box.
  2603. * @param {number} aspectRatio - The new aspect ratio.
  2604. * @returns {Cropper} this
  2605. */
  2606. setAspectRatio: function setAspectRatio(aspectRatio) {
  2607. var options = this.options;
  2608. if (!this.disabled && !isUndefined(aspectRatio)) {
  2609. // 0 -> NaN
  2610. options.aspectRatio = Math.max(0, aspectRatio) || NaN;
  2611. if (this.ready) {
  2612. this.initCropBox();
  2613. if (this.cropped) {
  2614. this.renderCropBox();
  2615. }
  2616. }
  2617. }
  2618. return this;
  2619. },
  2620. /**
  2621. * Change the drag mode.
  2622. * @param {string} mode - The new drag mode.
  2623. * @returns {Cropper} this
  2624. */
  2625. setDragMode: function setDragMode(mode) {
  2626. var options = this.options,
  2627. dragBox = this.dragBox,
  2628. face = this.face;
  2629. if (this.ready && !this.disabled) {
  2630. var croppable = mode === DRAG_MODE_CROP;
  2631. var movable = options.movable && mode === DRAG_MODE_MOVE;
  2632. mode = croppable || movable ? mode : DRAG_MODE_NONE;
  2633. options.dragMode = mode;
  2634. setData(dragBox, DATA_ACTION, mode);
  2635. toggleClass(dragBox, CLASS_CROP, croppable);
  2636. toggleClass(dragBox, CLASS_MOVE, movable);
  2637. if (!options.cropBoxMovable) {
  2638. // Sync drag mode to crop box when it is not movable
  2639. setData(face, DATA_ACTION, mode);
  2640. toggleClass(face, CLASS_CROP, croppable);
  2641. toggleClass(face, CLASS_MOVE, movable);
  2642. }
  2643. }
  2644. return this;
  2645. }
  2646. };
  2647. var AnotherCropper = WINDOW.Cropper;
  2648. var Cropper = function () {
  2649. /**
  2650. * Create a new Cropper.
  2651. * @param {Element} element - The target element for cropping.
  2652. * @param {Object} [options={}] - The configuration options.
  2653. */
  2654. function Cropper(element) {
  2655. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2656. classCallCheck(this, Cropper);
  2657. if (!element || !REGEXP_TAG_NAME.test(element.tagName)) {
  2658. throw new Error('The first argument is required and must be an <img> or <canvas> element.');
  2659. }
  2660. this.element = element;
  2661. this.options = assign({}, DEFAULTS, isPlainObject(options) && options);
  2662. this.cropped = false;
  2663. this.disabled = false;
  2664. this.pointers = {};
  2665. this.ready = false;
  2666. this.reloading = false;
  2667. this.replaced = false;
  2668. this.sized = false;
  2669. this.sizing = false;
  2670. this.init();
  2671. }
  2672. createClass(Cropper, [{
  2673. key: 'init',
  2674. value: function init() {
  2675. var element = this.element;
  2676. var tagName = element.tagName.toLowerCase();
  2677. var url = void 0;
  2678. if (getData(element, NAMESPACE)) {
  2679. return;
  2680. }
  2681. setData(element, NAMESPACE, this);
  2682. if (tagName === 'img') {
  2683. this.isImg = true;
  2684. // e.g.: "img/picture.jpg"
  2685. url = element.getAttribute('src') || '';
  2686. this.originalUrl = url;
  2687. // Stop when it's a blank image
  2688. if (!url) {
  2689. return;
  2690. }
  2691. // e.g.: "http://example.com/img/picture.jpg"
  2692. url = element.src;
  2693. } else if (tagName === 'canvas' && window.HTMLCanvasElement) {
  2694. url = element.toDataURL();
  2695. }
  2696. this.load(url);
  2697. }
  2698. }, {
  2699. key: 'load',
  2700. value: function load(url) {
  2701. var _this = this;
  2702. if (!url) {
  2703. return;
  2704. }
  2705. this.url = url;
  2706. this.imageData = {};
  2707. var element = this.element,
  2708. options = this.options;
  2709. if (!options.checkOrientation || !window.ArrayBuffer) {
  2710. this.clone();
  2711. return;
  2712. }
  2713. // XMLHttpRequest disallows to open a Data URL in some browsers like IE11 and Safari
  2714. if (REGEXP_DATA_URL.test(url)) {
  2715. if (REGEXP_DATA_URL_JPEG.test(url)) {
  2716. this.read(dataURLToArrayBuffer(url));
  2717. } else {
  2718. this.clone();
  2719. }
  2720. return;
  2721. }
  2722. var xhr = new XMLHttpRequest();
  2723. this.reloading = true;
  2724. this.xhr = xhr;
  2725. var done = function done() {
  2726. _this.reloading = false;
  2727. _this.xhr = null;
  2728. };
  2729. xhr.ontimeout = done;
  2730. xhr.onabort = done;
  2731. xhr.onerror = function () {
  2732. done();
  2733. _this.clone();
  2734. };
  2735. xhr.onload = function () {
  2736. done();
  2737. _this.read(xhr.response);
  2738. };
  2739. // Bust cache when there is a "crossOrigin" property
  2740. if (options.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) {
  2741. url = addTimestamp(url);
  2742. }
  2743. xhr.open('get', url);
  2744. xhr.responseType = 'arraybuffer';
  2745. xhr.withCredentials = element.crossOrigin === 'use-credentials';
  2746. xhr.send();
  2747. }
  2748. }, {
  2749. key: 'read',
  2750. value: function read(arrayBuffer) {
  2751. var options = this.options,
  2752. imageData = this.imageData;
  2753. var orientation = getOrientation(arrayBuffer);
  2754. var rotate = 0;
  2755. var scaleX = 1;
  2756. var scaleY = 1;
  2757. if (orientation > 1) {
  2758. this.url = arrayBufferToDataURL(arrayBuffer, 'image/jpeg');
  2759. var _parseOrientation = parseOrientation(orientation);
  2760. rotate = _parseOrientation.rotate;
  2761. scaleX = _parseOrientation.scaleX;
  2762. scaleY = _parseOrientation.scaleY;
  2763. }
  2764. if (options.rotatable) {
  2765. imageData.rotate = rotate;
  2766. }
  2767. if (options.scalable) {
  2768. imageData.scaleX = scaleX;
  2769. imageData.scaleY = scaleY;
  2770. }
  2771. this.clone();
  2772. }
  2773. }, {
  2774. key: 'clone',
  2775. value: function clone() {
  2776. var element = this.element,
  2777. url = this.url;
  2778. var crossOrigin = void 0;
  2779. var crossOriginUrl = void 0;
  2780. if (this.options.checkCrossOrigin && isCrossOriginURL(url)) {
  2781. crossOrigin = element.crossOrigin;
  2782. if (crossOrigin) {
  2783. crossOriginUrl = url;
  2784. } else {
  2785. crossOrigin = 'anonymous';
  2786. // Bust cache when there is not a "crossOrigin" property
  2787. crossOriginUrl = addTimestamp(url);
  2788. }
  2789. }
  2790. this.crossOrigin = crossOrigin;
  2791. this.crossOriginUrl = crossOriginUrl;
  2792. var image = document.createElement('img');
  2793. if (crossOrigin) {
  2794. image.crossOrigin = crossOrigin;
  2795. }
  2796. image.src = crossOriginUrl || url;
  2797. var start = this.start.bind(this);
  2798. var stop = this.stop.bind(this);
  2799. this.image = image;
  2800. this.onStart = start;
  2801. this.onStop = stop;
  2802. if (this.isImg) {
  2803. if (element.complete) {
  2804. // start asynchronously to keep `this.cropper` is accessible in `ready` event handler.
  2805. this.timeout = setTimeout(start, 0);
  2806. } else {
  2807. addListener(element, EVENT_LOAD, start, {
  2808. once: true
  2809. });
  2810. }
  2811. } else {
  2812. image.onload = start;
  2813. image.onerror = stop;
  2814. addClass(image, CLASS_HIDE);
  2815. element.parentNode.insertBefore(image, element.nextSibling);
  2816. }
  2817. }
  2818. }, {
  2819. key: 'start',
  2820. value: function start(event) {
  2821. var _this2 = this;
  2822. var image = this.isImg ? this.element : this.image;
  2823. if (event) {
  2824. image.onload = null;
  2825. image.onerror = null;
  2826. }
  2827. this.sizing = true;
  2828. var IS_SAFARI = WINDOW.navigator && /(Macintosh|iPhone|iPod|iPad).*AppleWebKit/i.test(WINDOW.navigator.userAgent);
  2829. var done = function done(naturalWidth, naturalHeight) {
  2830. assign(_this2.imageData, {
  2831. naturalWidth: naturalWidth,
  2832. naturalHeight: naturalHeight,
  2833. aspectRatio: naturalWidth / naturalHeight
  2834. });
  2835. _this2.sizing = false;
  2836. _this2.sized = true;
  2837. _this2.build();
  2838. };
  2839. // Modern browsers (except Safari)
  2840. if (image.naturalWidth && !IS_SAFARI) {
  2841. done(image.naturalWidth, image.naturalHeight);
  2842. return;
  2843. }
  2844. var sizingImage = document.createElement('img');
  2845. var body = document.body || document.documentElement;
  2846. this.sizingImage = sizingImage;
  2847. sizingImage.onload = function () {
  2848. done(sizingImage.width, sizingImage.height);
  2849. if (!IS_SAFARI) {
  2850. body.removeChild(sizingImage);
  2851. }
  2852. };
  2853. sizingImage.src = image.src;
  2854. // iOS Safari will convert the image automatically
  2855. // with its orientation once append it into DOM (#279)
  2856. if (!IS_SAFARI) {
  2857. sizingImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;';
  2858. body.appendChild(sizingImage);
  2859. }
  2860. }
  2861. }, {
  2862. key: 'stop',
  2863. value: function stop() {
  2864. var image = this.image;
  2865. image.onload = null;
  2866. image.onerror = null;
  2867. image.parentNode.removeChild(image);
  2868. this.image = null;
  2869. }
  2870. }, {
  2871. key: 'build',
  2872. value: function build() {
  2873. if (!this.sized || this.ready) {
  2874. return;
  2875. }
  2876. var element = this.element,
  2877. options = this.options,
  2878. image = this.image;
  2879. // Create cropper elements
  2880. var container = element.parentNode;
  2881. var template = document.createElement('div');
  2882. template.innerHTML = TEMPLATE;
  2883. var cropper = template.querySelector('.' + NAMESPACE + '-container');
  2884. var canvas = cropper.querySelector('.' + NAMESPACE + '-canvas');
  2885. var dragBox = cropper.querySelector('.' + NAMESPACE + '-drag-box');
  2886. var cropBox = cropper.querySelector('.' + NAMESPACE + '-crop-box');
  2887. var face = cropBox.querySelector('.' + NAMESPACE + '-face');
  2888. this.container = container;
  2889. this.cropper = cropper;
  2890. this.canvas = canvas;
  2891. this.dragBox = dragBox;
  2892. this.cropBox = cropBox;
  2893. this.viewBox = cropper.querySelector('.' + NAMESPACE + '-view-box');
  2894. this.face = face;
  2895. canvas.appendChild(image);
  2896. // Hide the original image
  2897. addClass(element, CLASS_HIDDEN);
  2898. // Inserts the cropper after to the current image
  2899. container.insertBefore(cropper, element.nextSibling);
  2900. // Show the image if is hidden
  2901. if (!this.isImg) {
  2902. removeClass(image, CLASS_HIDE);
  2903. }
  2904. this.initPreview();
  2905. this.bind();
  2906. options.aspectRatio = Math.max(0, options.aspectRatio) || NaN;
  2907. options.viewMode = Math.max(0, Math.min(3, Math.round(options.viewMode))) || 0;
  2908. addClass(cropBox, CLASS_HIDDEN);
  2909. if (!options.guides) {
  2910. addClass(cropBox.getElementsByClassName(NAMESPACE + '-dashed'), CLASS_HIDDEN);
  2911. }
  2912. if (!options.center) {
  2913. addClass(cropBox.getElementsByClassName(NAMESPACE + '-center'), CLASS_HIDDEN);
  2914. }
  2915. if (options.background) {
  2916. addClass(cropper, NAMESPACE + '-bg');
  2917. }
  2918. if (!options.highlight) {
  2919. addClass(face, CLASS_INVISIBLE);
  2920. }
  2921. if (options.cropBoxMovable) {
  2922. addClass(face, CLASS_MOVE);
  2923. setData(face, DATA_ACTION, ACTION_ALL);
  2924. }
  2925. if (!options.cropBoxResizable) {
  2926. addClass(cropBox.getElementsByClassName(NAMESPACE + '-line'), CLASS_HIDDEN);
  2927. addClass(cropBox.getElementsByClassName(NAMESPACE + '-point'), CLASS_HIDDEN);
  2928. }
  2929. this.render();
  2930. this.ready = true;
  2931. this.setDragMode(options.dragMode);
  2932. if (options.autoCrop) {
  2933. this.crop();
  2934. }
  2935. this.setData(options.data);
  2936. if (isFunction(options.ready)) {
  2937. addListener(element, EVENT_READY, options.ready, {
  2938. once: true
  2939. });
  2940. }
  2941. dispatchEvent(element, EVENT_READY);
  2942. }
  2943. }, {
  2944. key: 'unbuild',
  2945. value: function unbuild() {
  2946. if (!this.ready) {
  2947. return;
  2948. }
  2949. this.ready = false;
  2950. this.unbind();
  2951. this.resetPreview();
  2952. this.cropper.parentNode.removeChild(this.cropper);
  2953. removeClass(this.element, CLASS_HIDDEN);
  2954. }
  2955. }, {
  2956. key: 'uncreate',
  2957. value: function uncreate() {
  2958. var element = this.element;
  2959. if (this.ready) {
  2960. this.unbuild();
  2961. this.ready = false;
  2962. this.cropped = false;
  2963. } else if (this.sizing) {
  2964. this.sizingImage.onload = null;
  2965. this.sizing = false;
  2966. this.sized = false;
  2967. } else if (this.reloading) {
  2968. this.xhr.abort();
  2969. } else if (this.isImg) {
  2970. if (element.complete) {
  2971. clearTimeout(this.timeout);
  2972. } else {
  2973. removeListener(element, EVENT_LOAD, this.onStart);
  2974. }
  2975. } else if (this.image) {
  2976. this.stop();
  2977. }
  2978. }
  2979. /**
  2980. * Get the no conflict cropper class.
  2981. * @returns {Cropper} The cropper class.
  2982. */
  2983. }], [{
  2984. key: 'noConflict',
  2985. value: function noConflict() {
  2986. window.Cropper = AnotherCropper;
  2987. return Cropper;
  2988. }
  2989. /**
  2990. * Change the default options.
  2991. * @param {Object} options - The new default options.
  2992. */
  2993. }, {
  2994. key: 'setDefaults',
  2995. value: function setDefaults(options) {
  2996. assign(DEFAULTS, isPlainObject(options) && options);
  2997. }
  2998. }]);
  2999. return Cropper;
  3000. }();
  3001. assign(Cropper.prototype, render, preview, events, handlers, change, methods);
  3002. if ($.fn) {
  3003. var AnotherCropper$1 = $.fn.cropper;
  3004. var NAMESPACE$1 = 'cropper';
  3005. $.fn.cropper = function jQueryCropper(option) {
  3006. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  3007. args[_key - 1] = arguments[_key];
  3008. }
  3009. var result = void 0;
  3010. this.each(function (i, element) {
  3011. var $element = $(element);
  3012. var isDestroy = option === 'destroy';
  3013. var cropper = $element.data(NAMESPACE$1);
  3014. if (!cropper) {
  3015. if (isDestroy) {
  3016. return;
  3017. }
  3018. var options = $.extend({}, $element.data(), $.isPlainObject(option) && option);
  3019. cropper = new Cropper(element, options);
  3020. $element.data(NAMESPACE$1, cropper);
  3021. }
  3022. if (typeof option === 'string') {
  3023. var fn = cropper[option];
  3024. if ($.isFunction(fn)) {
  3025. result = fn.apply(cropper, args);
  3026. if (result === cropper) {
  3027. result = undefined;
  3028. }
  3029. if (isDestroy) {
  3030. $element.removeData(NAMESPACE$1);
  3031. }
  3032. }
  3033. }
  3034. });
  3035. return result !== undefined ? result : this;
  3036. };
  3037. $.fn.cropper.Constructor = Cropper;
  3038. $.fn.cropper.setDefaults = Cropper.setDefaults;
  3039. $.fn.cropper.noConflict = function noConflict() {
  3040. $.fn.cropper = AnotherCropper$1;
  3041. return this;
  3042. };
  3043. }
  3044. })));