cropper.js 110 KB

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