cropper.esm.js 105 KB

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