cropper.common.js 104 KB

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