cropper.common.js 105 KB

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