cropper.js 111 KB

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