cropper.js 111 KB

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