cropper.esm.js 104 KB

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