cropper.js 111 KB

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