cropper.js 112 KB

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