cropper.js 112 KB

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