cropper.js 111 KB

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