cropper.esm.js 104 KB

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