cropper.common.js 104 KB

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