cropper.common.js 105 KB

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