cropper.common.js 105 KB

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