AI销管
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

weCropper.js 31 KiB

2 anos atrás
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. /**
  2. * we-cropper v1.3.9
  3. * (c) 2020 dlhandsome
  4. * @license MIT
  5. */
  6. (function(global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global.WeCropper = factory());
  10. }(this, (function() {
  11. 'use strict';
  12. var device = void 0;
  13. var TOUCH_STATE = ['touchstarted', 'touchmoved', 'touchended'];
  14. function firstLetterUpper(str) {
  15. return str.charAt(0).toUpperCase() + str.slice(1)
  16. }
  17. function setTouchState(instance) {
  18. var arg = [],
  19. len = arguments.length - 1;
  20. while (len-- > 0) arg[len] = arguments[len + 1];
  21. TOUCH_STATE.forEach(function(key, i) {
  22. if (arg[i] !== undefined) {
  23. instance[key] = arg[i];
  24. }
  25. });
  26. }
  27. function validator(instance, o) {
  28. Object.defineProperties(instance, o);
  29. }
  30. function getDevice() {
  31. if (!device) {
  32. device = uni.getSystemInfoSync();
  33. }
  34. return device
  35. }
  36. var tmp = {};
  37. var ref = getDevice();
  38. var pixelRatio = ref.pixelRatio;
  39. var DEFAULT = {
  40. id: {
  41. default: 'cropper',
  42. get: function get() {
  43. return tmp.id
  44. },
  45. set: function set(value) {
  46. if (typeof(value) !== 'string') {
  47. console.error(("id:" + value + " is invalid"));
  48. }
  49. tmp.id = value;
  50. }
  51. },
  52. width: {
  53. default: 750,
  54. get: function get() {
  55. return tmp.width
  56. },
  57. set: function set(value) {
  58. if (typeof(value) !== 'number') {
  59. console.error(("width:" + value + " is invalid"));
  60. }
  61. tmp.width = value;
  62. }
  63. },
  64. height: {
  65. default: 750,
  66. get: function get() {
  67. return tmp.height
  68. },
  69. set: function set(value) {
  70. if (typeof(value) !== 'number') {
  71. console.error(("height:" + value + " is invalid"));
  72. }
  73. tmp.height = value;
  74. }
  75. },
  76. pixelRatio: {
  77. default: pixelRatio,
  78. get: function get() {
  79. return tmp.pixelRatio
  80. },
  81. set: function set(value) {
  82. if (typeof(value) !== 'number') {
  83. console.error(("pixelRatio:" + value + " is invalid"));
  84. }
  85. tmp.pixelRatio = value;
  86. }
  87. },
  88. scale: {
  89. default: 2.5,
  90. get: function get() {
  91. return tmp.scale
  92. },
  93. set: function set(value) {
  94. if (typeof(value) !== 'number') {
  95. console.error(("scale:" + value + " is invalid"));
  96. }
  97. tmp.scale = value;
  98. }
  99. },
  100. zoom: {
  101. default: 5,
  102. get: function get() {
  103. return tmp.zoom
  104. },
  105. set: function set(value) {
  106. if (typeof(value) !== 'number') {
  107. console.error(("zoom:" + value + " is invalid"));
  108. } else if (value < 0 || value > 10) {
  109. console.error("zoom should be ranged in 0 ~ 10");
  110. }
  111. tmp.zoom = value;
  112. }
  113. },
  114. src: {
  115. default: '',
  116. get: function get() {
  117. return tmp.src
  118. },
  119. set: function set(value) {
  120. if (typeof(value) !== 'string') {
  121. console.error(("src:" + value + " is invalid"));
  122. }
  123. tmp.src = value;
  124. }
  125. },
  126. cut: {
  127. default: {},
  128. get: function get() {
  129. return tmp.cut
  130. },
  131. set: function set(value) {
  132. if (typeof(value) !== 'object') {
  133. console.error(("cut:" + value + " is invalid"));
  134. }
  135. tmp.cut = value;
  136. }
  137. },
  138. boundStyle: {
  139. default: {},
  140. get: function get() {
  141. return tmp.boundStyle
  142. },
  143. set: function set(value) {
  144. if (typeof(value) !== 'object') {
  145. console.error(("boundStyle:" + value + " is invalid"));
  146. }
  147. tmp.boundStyle = value;
  148. }
  149. },
  150. onReady: {
  151. default: null,
  152. get: function get() {
  153. return tmp.ready
  154. },
  155. set: function set(value) {
  156. tmp.ready = value;
  157. }
  158. },
  159. onBeforeImageLoad: {
  160. default: null,
  161. get: function get() {
  162. return tmp.beforeImageLoad
  163. },
  164. set: function set(value) {
  165. tmp.beforeImageLoad = value;
  166. }
  167. },
  168. onImageLoad: {
  169. default: null,
  170. get: function get() {
  171. return tmp.imageLoad
  172. },
  173. set: function set(value) {
  174. tmp.imageLoad = value;
  175. }
  176. },
  177. onBeforeDraw: {
  178. default: null,
  179. get: function get() {
  180. return tmp.beforeDraw
  181. },
  182. set: function set(value) {
  183. tmp.beforeDraw = value;
  184. }
  185. }
  186. };
  187. var ref$1 = getDevice();
  188. var windowWidth = ref$1.windowWidth;
  189. function prepare() {
  190. var self = this;
  191. // v1.4.0 版本中将不再自动绑定we-cropper实例
  192. self.attachPage = function() {
  193. var pages = getCurrentPages();
  194. // 获取到当前page上下文
  195. var pageContext = pages[pages.length - 1];
  196. // 把this依附在Page上下文的wecropper属性上,便于在page钩子函数中访问
  197. Object.defineProperty(pageContext, 'wecropper', {
  198. get: function get() {
  199. console.warn(
  200. 'Instance will not be automatically bound to the page after v1.4.0\n\n' +
  201. 'Please use a custom instance name instead\n\n' +
  202. 'Example: \n' +
  203. 'this.mycropper = new WeCropper(options)\n\n' +
  204. '// ...\n' +
  205. 'this.mycropper.getCropperImage()'
  206. );
  207. return self
  208. },
  209. configurable: true
  210. });
  211. };
  212. self.createCtx = function() {
  213. var id = self.id;
  214. var targetId = self.targetId;
  215. if (id) {
  216. self.ctx = self.ctx || uni.createCanvasContext(id);
  217. self.targetCtx = self.targetCtx || uni.createCanvasContext(targetId);
  218. } else {
  219. console.error("constructor: create canvas context failed, 'id' must be valuable");
  220. }
  221. };
  222. self.deviceRadio = windowWidth / 750;
  223. }
  224. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !==
  225. 'undefined' ? self : {};
  226. function createCommonjsModule(fn, module) {
  227. return module = {
  228. exports: {}
  229. }, fn(module, module.exports), module.exports;
  230. }
  231. var tools = createCommonjsModule(function(module, exports) {
  232. /**
  233. * String type check
  234. */
  235. exports.isStr = function(v) {
  236. return typeof v === 'string';
  237. };
  238. /**
  239. * Number type check
  240. */
  241. exports.isNum = function(v) {
  242. return typeof v === 'number';
  243. };
  244. /**
  245. * Array type check
  246. */
  247. exports.isArr = Array.isArray;
  248. /**
  249. * undefined type check
  250. */
  251. exports.isUndef = function(v) {
  252. return v === undefined;
  253. };
  254. exports.isTrue = function(v) {
  255. return v === true;
  256. };
  257. exports.isFalse = function(v) {
  258. return v === false;
  259. };
  260. /**
  261. * Function type check
  262. */
  263. exports.isFunc = function(v) {
  264. return typeof v === 'function';
  265. };
  266. /**
  267. * Quick object check - this is primarily used to tell
  268. * Objects from primitive values when we know the value
  269. * is a JSON-compliant type.
  270. */
  271. exports.isObj = exports.isObject = function(obj) {
  272. return obj !== null && typeof obj === 'object'
  273. };
  274. /**
  275. * Strict object type check. Only returns true
  276. * for plain JavaScript objects.
  277. */
  278. var _toString = Object.prototype.toString;
  279. exports.isPlainObject = function(obj) {
  280. return _toString.call(obj) === '[object Object]'
  281. };
  282. /**
  283. * Check whether the object has the property.
  284. */
  285. var hasOwnProperty = Object.prototype.hasOwnProperty;
  286. exports.hasOwn = function(obj, key) {
  287. return hasOwnProperty.call(obj, key)
  288. };
  289. /**
  290. * Perform no operation.
  291. * Stubbing args to make Flow happy without leaving useless transpiled code
  292. * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/)
  293. */
  294. exports.noop = function(a, b, c) {};
  295. /**
  296. * Check if val is a valid array index.
  297. */
  298. exports.isValidArrayIndex = function(val) {
  299. var n = parseFloat(String(val));
  300. return n >= 0 && Math.floor(n) === n && isFinite(val)
  301. };
  302. });
  303. var tools_7 = tools.isFunc;
  304. var tools_10 = tools.isPlainObject;
  305. var EVENT_TYPE = ['ready', 'beforeImageLoad', 'beforeDraw', 'imageLoad'];
  306. function observer() {
  307. var self = this;
  308. self.on = function(event, fn) {
  309. if (EVENT_TYPE.indexOf(event) > -1) {
  310. if (tools_7(fn)) {
  311. event === 'ready' ?
  312. fn(self) :
  313. self[("on" + (firstLetterUpper(event)))] = fn;
  314. }
  315. } else {
  316. console.error(("event: " + event + " is invalid"));
  317. }
  318. return self
  319. };
  320. }
  321. function wxPromise(fn) {
  322. return function(obj) {
  323. var args = [],
  324. len = arguments.length - 1;
  325. while (len-- > 0) args[len] = arguments[len + 1];
  326. if (obj === void 0) obj = {};
  327. return new Promise(function(resolve, reject) {
  328. obj.success = function(res) {
  329. resolve(res);
  330. };
  331. obj.fail = function(err) {
  332. reject(err);
  333. };
  334. fn.apply(void 0, [obj].concat(args));
  335. })
  336. }
  337. }
  338. function draw(ctx, reserve) {
  339. if (reserve === void 0) reserve = false;
  340. return new Promise(function(resolve) {
  341. ctx.draw(reserve, resolve);
  342. })
  343. }
  344. var getImageInfo = wxPromise(uni.getImageInfo);
  345. var canvasToTempFilePath = wxPromise(uni.canvasToTempFilePath);
  346. var base64 = createCommonjsModule(function(module, exports) {
  347. /*! http://mths.be/base64 v0.1.0 by @mathias | MIT license */
  348. (function(root) {
  349. // Detect free variables `exports`.
  350. var freeExports = 'object' == 'object' && exports;
  351. // Detect free variable `module`.
  352. var freeModule = 'object' == 'object' && module &&
  353. module.exports == freeExports && module;
  354. // Detect free variable `global`, from Node.js or Browserified code, and use
  355. // it as `root`.
  356. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
  357. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  358. root = freeGlobal;
  359. }
  360. /*--------------------------------------------------------------------------*/
  361. var InvalidCharacterError = function(message) {
  362. this.message = message;
  363. };
  364. InvalidCharacterError.prototype = new Error;
  365. InvalidCharacterError.prototype.name = 'InvalidCharacterError';
  366. var error = function(message) {
  367. // Note: the error messages used throughout this file match those used by
  368. // the native `atob`/`btoa` implementation in Chromium.
  369. throw new InvalidCharacterError(message);
  370. };
  371. var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  372. // http://whatwg.org/html/common-microsyntaxes.html#space-character
  373. var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g;
  374. // `decode` is designed to be fully compatible with `atob` as described in the
  375. // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob
  376. // The optimized base64-decoding algorithm used is based on @atk’s excellent
  377. // implementation. https://gist.github.com/atk/1020396
  378. var decode = function(input) {
  379. input = String(input)
  380. .replace(REGEX_SPACE_CHARACTERS, '');
  381. var length = input.length;
  382. if (length % 4 == 0) {
  383. input = input.replace(/==?$/, '');
  384. length = input.length;
  385. }
  386. if (
  387. length % 4 == 1 ||
  388. // http://whatwg.org/C#alphanumeric-ascii-characters
  389. /[^+a-zA-Z0-9/]/.test(input)
  390. ) {
  391. error(
  392. 'Invalid character: the string to be decoded is not correctly encoded.'
  393. );
  394. }
  395. var bitCounter = 0;
  396. var bitStorage;
  397. var buffer;
  398. var output = '';
  399. var position = -1;
  400. while (++position < length) {
  401. buffer = TABLE.indexOf(input.charAt(position));
  402. bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer;
  403. // Unless this is the first of a group of 4 characters…
  404. if (bitCounter++ % 4) {
  405. // …convert the first 8 bits to a single ASCII character.
  406. output += String.fromCharCode(
  407. 0xFF & bitStorage >> (-2 * bitCounter & 6)
  408. );
  409. }
  410. }
  411. return output;
  412. };
  413. // `encode` is designed to be fully compatible with `btoa` as described in the
  414. // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa
  415. var encode = function(input) {
  416. input = String(input);
  417. if (/[^\0-\xFF]/.test(input)) {
  418. // Note: no need to special-case astral symbols here, as surrogates are
  419. // matched, and the input is supposed to only contain ASCII anyway.
  420. error(
  421. 'The string to be encoded contains characters outside of the ' +
  422. 'Latin1 range.'
  423. );
  424. }
  425. var padding = input.length % 3;
  426. var output = '';
  427. var position = -1;
  428. var a;
  429. var b;
  430. var c;
  431. var buffer;
  432. // Make sure any padding is handled outside of the loop.
  433. var length = input.length - padding;
  434. while (++position < length) {
  435. // Read three bytes, i.e. 24 bits.
  436. a = input.charCodeAt(position) << 16;
  437. b = input.charCodeAt(++position) << 8;
  438. c = input.charCodeAt(++position);
  439. buffer = a + b + c;
  440. // Turn the 24 bits into four chunks of 6 bits each, and append the
  441. // matching character for each of them to the output.
  442. output += (
  443. TABLE.charAt(buffer >> 18 & 0x3F) +
  444. TABLE.charAt(buffer >> 12 & 0x3F) +
  445. TABLE.charAt(buffer >> 6 & 0x3F) +
  446. TABLE.charAt(buffer & 0x3F)
  447. );
  448. }
  449. if (padding == 2) {
  450. a = input.charCodeAt(position) << 8;
  451. b = input.charCodeAt(++position);
  452. buffer = a + b;
  453. output += (
  454. TABLE.charAt(buffer >> 10) +
  455. TABLE.charAt((buffer >> 4) & 0x3F) +
  456. TABLE.charAt((buffer << 2) & 0x3F) +
  457. '='
  458. );
  459. } else if (padding == 1) {
  460. buffer = input.charCodeAt(position);
  461. output += (
  462. TABLE.charAt(buffer >> 2) +
  463. TABLE.charAt((buffer << 4) & 0x3F) +
  464. '=='
  465. );
  466. }
  467. return output;
  468. };
  469. var base64 = {
  470. 'encode': encode,
  471. 'decode': decode,
  472. 'version': '0.1.0'
  473. };
  474. // Some AMD build optimizers, like r.js, check for specific condition patterns
  475. // like the following:
  476. if (
  477. typeof undefined == 'function' &&
  478. typeof undefined.amd == 'object' &&
  479. undefined.amd
  480. ) {
  481. undefined(function() {
  482. return base64;
  483. });
  484. } else if (freeExports && !freeExports.nodeType) {
  485. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  486. freeModule.exports = base64;
  487. } else { // in Narwhal or RingoJS v0.7.0-
  488. for (var key in base64) {
  489. base64.hasOwnProperty(key) && (freeExports[key] = base64[key]);
  490. }
  491. }
  492. } else { // in Rhino or a web browser
  493. root.base64 = base64;
  494. }
  495. }(commonjsGlobal));
  496. });
  497. function makeURI(strData, type) {
  498. return 'data:' + type + ';base64,' + strData
  499. }
  500. function fixType(type) {
  501. type = type.toLowerCase().replace(/jpg/i, 'jpeg');
  502. var r = type.match(/png|jpeg|bmp|gif/)[0];
  503. return 'image/' + r
  504. }
  505. function encodeData(data) {
  506. var str = '';
  507. if (typeof data === 'string') {
  508. str = data;
  509. } else {
  510. for (var i = 0; i < data.length; i++) {
  511. str += String.fromCharCode(data[i]);
  512. }
  513. }
  514. return base64.encode(str)
  515. }
  516. /**
  517. * 获取图像区域隐含的像素数据
  518. * @param canvasId canvas标识
  519. * @param x 将要被提取的图像数据矩形区域的左上角 x 坐标
  520. * @param y 将要被提取的图像数据矩形区域的左上角 y 坐标
  521. * @param width 将要被提取的图像数据矩形区域的宽度
  522. * @param height 将要被提取的图像数据矩形区域的高度
  523. * @param done 完成回调
  524. */
  525. function getImageData(canvasId, x, y, width, height, done) {
  526. uni.canvasGetImageData({
  527. canvasId: canvasId,
  528. x: x,
  529. y: y,
  530. width: width,
  531. height: height,
  532. success: function success(res) {
  533. done(res, null);
  534. },
  535. fail: function fail(res) {
  536. done(null, res);
  537. }
  538. });
  539. }
  540. /**
  541. * 生成bmp格式图片
  542. * 按照规则生成图片响应头和响应体
  543. * @param oData 用来描述 canvas 区域隐含的像素数据 { data, width, height } = oData
  544. * @returns {*} base64字符串
  545. */
  546. function genBitmapImage(oData) {
  547. //
  548. // BITMAPFILEHEADER: http://msdn.microsoft.com/en-us/library/windows/desktop/dd183374(v=vs.85).aspx
  549. // BITMAPINFOHEADER: http://msdn.microsoft.com/en-us/library/dd183376.aspx
  550. //
  551. var biWidth = oData.width;
  552. var biHeight = oData.height;
  553. var biSizeImage = biWidth * biHeight * 3;
  554. var bfSize = biSizeImage + 54; // total header size = 54 bytes
  555. //
  556. // typedef struct tagBITMAPFILEHEADER {
  557. // WORD bfType;
  558. // DWORD bfSize;
  559. // WORD bfReserved1;
  560. // WORD bfReserved2;
  561. // DWORD bfOffBits;
  562. // } BITMAPFILEHEADER;
  563. //
  564. var BITMAPFILEHEADER = [
  565. // WORD bfType -- The file type signature; must be "BM"
  566. 0x42, 0x4D,
  567. // DWORD bfSize -- The size, in bytes, of the bitmap file
  568. bfSize & 0xff, bfSize >> 8 & 0xff, bfSize >> 16 & 0xff, bfSize >> 24 & 0xff,
  569. // WORD bfReserved1 -- Reserved; must be zero
  570. 0, 0,
  571. // WORD bfReserved2 -- Reserved; must be zero
  572. 0, 0,
  573. // DWORD bfOffBits -- The offset, in bytes, from the beginning of the BITMAPFILEHEADER structure to the bitmap bits.
  574. 54, 0, 0, 0
  575. ];
  576. //
  577. // typedef struct tagBITMAPINFOHEADER {
  578. // DWORD biSize;
  579. // LONG biWidth;
  580. // LONG biHeight;
  581. // WORD biPlanes;
  582. // WORD biBitCount;
  583. // DWORD biCompression;
  584. // DWORD biSizeImage;
  585. // LONG biXPelsPerMeter;
  586. // LONG biYPelsPerMeter;
  587. // DWORD biClrUsed;
  588. // DWORD biClrImportant;
  589. // } BITMAPINFOHEADER, *PBITMAPINFOHEADER;
  590. //
  591. var BITMAPINFOHEADER = [
  592. // DWORD biSize -- The number of bytes required by the structure
  593. 40, 0, 0, 0,
  594. // LONG biWidth -- The width of the bitmap, in pixels
  595. biWidth & 0xff, biWidth >> 8 & 0xff, biWidth >> 16 & 0xff, biWidth >> 24 & 0xff,
  596. // LONG biHeight -- The height of the bitmap, in pixels
  597. biHeight & 0xff, biHeight >> 8 & 0xff, biHeight >> 16 & 0xff, biHeight >> 24 & 0xff,
  598. // WORD biPlanes -- The number of planes for the target device. This value must be set to 1
  599. 1, 0,
  600. // WORD biBitCount -- The number of bits-per-pixel, 24 bits-per-pixel -- the bitmap
  601. // has a maximum of 2^24 colors (16777216, Truecolor)
  602. 24, 0,
  603. // DWORD biCompression -- The type of compression, BI_RGB (code 0) -- uncompressed
  604. 0, 0, 0, 0,
  605. // DWORD biSizeImage -- The size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps
  606. biSizeImage & 0xff, biSizeImage >> 8 & 0xff, biSizeImage >> 16 & 0xff, biSizeImage >> 24 & 0xff,
  607. // LONG biXPelsPerMeter, unused
  608. 0, 0, 0, 0,
  609. // LONG biYPelsPerMeter, unused
  610. 0, 0, 0, 0,
  611. // DWORD biClrUsed, the number of color indexes of palette, unused
  612. 0, 0, 0, 0,
  613. // DWORD biClrImportant, unused
  614. 0, 0, 0, 0
  615. ];
  616. var iPadding = (4 - ((biWidth * 3) % 4)) % 4;
  617. var aImgData = oData.data;
  618. var strPixelData = '';
  619. var biWidth4 = biWidth << 2;
  620. var y = biHeight;
  621. var fromCharCode = String.fromCharCode;
  622. do {
  623. var iOffsetY = biWidth4 * (y - 1);
  624. var strPixelRow = '';
  625. for (var x = 0; x < biWidth; x++) {
  626. var iOffsetX = x << 2;
  627. strPixelRow += fromCharCode(aImgData[iOffsetY + iOffsetX + 2]) +
  628. fromCharCode(aImgData[iOffsetY + iOffsetX + 1]) +
  629. fromCharCode(aImgData[iOffsetY + iOffsetX]);
  630. }
  631. for (var c = 0; c < iPadding; c++) {
  632. strPixelRow += String.fromCharCode(0);
  633. }
  634. strPixelData += strPixelRow;
  635. } while (--y)
  636. var strEncoded = encodeData(BITMAPFILEHEADER.concat(BITMAPINFOHEADER)) + encodeData(strPixelData);
  637. return strEncoded
  638. }
  639. /**
  640. * 转换为图片base64
  641. * @param canvasId canvas标识
  642. * @param x 将要被提取的图像数据矩形区域的左上角 x 坐标
  643. * @param y 将要被提取的图像数据矩形区域的左上角 y 坐标
  644. * @param width 将要被提取的图像数据矩形区域的宽度
  645. * @param height 将要被提取的图像数据矩形区域的高度
  646. * @param type 转换图片类型
  647. * @param done 完成回调
  648. */
  649. function convertToImage(canvasId, x, y, width, height, type, done) {
  650. if (done === void 0) done = function() {};
  651. if (type === undefined) {
  652. type = 'png';
  653. }
  654. type = fixType(type);
  655. if (/bmp/.test(type)) {
  656. getImageData(canvasId, x, y, width, height, function(data, err) {
  657. var strData = genBitmapImage(data);
  658. tools_7(done) && done(makeURI(strData, 'image/' + type), err);
  659. });
  660. } else {
  661. console.error('暂不支持生成\'' + type + '\'类型的base64图片');
  662. }
  663. }
  664. var CanvasToBase64 = {
  665. convertToImage: convertToImage,
  666. // convertToPNG: function (width, height, done) {
  667. // return convertToImage(width, height, 'png', done)
  668. // },
  669. // convertToJPEG: function (width, height, done) {
  670. // return convertToImage(width, height, 'jpeg', done)
  671. // },
  672. // convertToGIF: function (width, height, done) {
  673. // return convertToImage(width, height, 'gif', done)
  674. // },
  675. convertToBMP: function(ref, done) {
  676. if (ref === void 0) ref = {};
  677. var canvasId = ref.canvasId;
  678. var x = ref.x;
  679. var y = ref.y;
  680. var width = ref.width;
  681. var height = ref.height;
  682. if (done === void 0) done = function() {};
  683. return convertToImage(canvasId, x, y, width, height, 'bmp', done)
  684. }
  685. };
  686. function methods() {
  687. var self = this;
  688. var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
  689. var boundHeight = self.height; // 裁剪框默认高度,即整个画布高度
  690. var id = self.id;
  691. var targetId = self.targetId;
  692. var pixelRatio = self.pixelRatio;
  693. var ref = self.cut;
  694. var x = ref.x;
  695. if (x === void 0) x = 0;
  696. var y = ref.y;
  697. if (y === void 0) y = 0;
  698. var width = ref.width;
  699. if (width === void 0) width = boundWidth;
  700. var height = ref.height;
  701. if (height === void 0) height = boundHeight;
  702. self.updateCanvas = function(done) {
  703. if (self.croperTarget) {
  704. // 画布绘制图片
  705. self.ctx.drawImage(
  706. self.croperTarget,
  707. self.imgLeft,
  708. self.imgTop,
  709. self.scaleWidth,
  710. self.scaleHeight
  711. );
  712. }
  713. tools_7(self.onBeforeDraw) && self.onBeforeDraw(self.ctx, self);
  714. self.setBoundStyle(self.boundStyle); // 设置边界样式
  715. self.ctx.draw(false, done);
  716. return self
  717. };
  718. self.pushOrigin = self.pushOrign = function(src) {
  719. self.src = src;
  720. tools_7(self.onBeforeImageLoad) && self.onBeforeImageLoad(self.ctx, self);
  721. return getImageInfo({
  722. src: src
  723. })
  724. .then(function(res) {
  725. var innerAspectRadio = res.width / res.height;
  726. var customAspectRadio = width / height;
  727. self.croperTarget = res.path;
  728. if (innerAspectRadio < customAspectRadio) {
  729. self.rectX = x;
  730. self.baseWidth = width;
  731. self.baseHeight = width / innerAspectRadio;
  732. self.rectY = y - Math.abs((height - self.baseHeight) / 2);
  733. } else {
  734. self.rectY = y;
  735. self.baseWidth = height * innerAspectRadio;
  736. self.baseHeight = height;
  737. self.rectX = x - Math.abs((width - self.baseWidth) / 2);
  738. }
  739. self.imgLeft = self.rectX;
  740. self.imgTop = self.rectY;
  741. self.scaleWidth = self.baseWidth;
  742. self.scaleHeight = self.baseHeight;
  743. self.update();
  744. return new Promise(function(resolve) {
  745. self.updateCanvas(resolve);
  746. })
  747. })
  748. .then(function() {
  749. tools_7(self.onImageLoad) && self.onImageLoad(self.ctx, self);
  750. })
  751. };
  752. self.removeImage = function() {
  753. self.src = '';
  754. self.croperTarget = '';
  755. return draw(self.ctx)
  756. };
  757. self.getCropperBase64 = function(done) {
  758. if (done === void 0) done = function() {};
  759. CanvasToBase64.convertToBMP({
  760. canvasId: id,
  761. x: x,
  762. y: y,
  763. width: width,
  764. height: height
  765. }, done);
  766. };
  767. self.getCropperImage = function(opt, fn) {
  768. var customOptions = opt;
  769. var canvasOptions = {
  770. canvasId: id,
  771. x: x,
  772. y: y,
  773. width: width,
  774. height: height
  775. };
  776. var task = function() {
  777. return Promise.resolve();
  778. };
  779. if (
  780. tools_10(customOptions) &&
  781. customOptions.original
  782. ) {
  783. // original mode
  784. task = function() {
  785. self.targetCtx.drawImage(
  786. self.croperTarget,
  787. self.imgLeft * pixelRatio,
  788. self.imgTop * pixelRatio,
  789. self.scaleWidth * pixelRatio,
  790. self.scaleHeight * pixelRatio
  791. );
  792. canvasOptions = {
  793. canvasId: targetId,
  794. x: x * pixelRatio,
  795. y: y * pixelRatio,
  796. width: width * pixelRatio,
  797. height: height * pixelRatio
  798. };
  799. return draw(self.targetCtx)
  800. };
  801. }
  802. return task()
  803. .then(function() {
  804. if (tools_10(customOptions)) {
  805. canvasOptions = Object.assign({}, canvasOptions, customOptions);
  806. }
  807. if (tools_7(customOptions)) {
  808. fn = customOptions;
  809. }
  810. var arg = canvasOptions.componentContext ?
  811. [canvasOptions, canvasOptions.componentContext] :
  812. [canvasOptions];
  813. return canvasToTempFilePath.apply(null, arg)
  814. })
  815. .then(function(res) {
  816. var tempFilePath = res.tempFilePath;
  817. return tools_7(fn) ?
  818. fn.call(self, tempFilePath, null) :
  819. tempFilePath
  820. })
  821. .catch(function(err) {
  822. if (tools_7(fn)) {
  823. fn.call(self, null, err);
  824. } else {
  825. throw err
  826. }
  827. })
  828. };
  829. }
  830. /**
  831. * 获取最新缩放值
  832. * @param oldScale 上一次触摸结束后的缩放值
  833. * @param oldDistance 上一次触摸结束后的双指距离
  834. * @param zoom 缩放系数
  835. * @param touch0 第一指touch对象
  836. * @param touch1 第二指touch对象
  837. * @returns {*}
  838. */
  839. var getNewScale = function(oldScale, oldDistance, zoom, touch0, touch1) {
  840. var xMove, yMove, newDistance;
  841. // 计算二指最新距离
  842. xMove = Math.round(touch1.x - touch0.x);
  843. yMove = Math.round(touch1.y - touch0.y);
  844. newDistance = Math.round(Math.sqrt(xMove * xMove + yMove * yMove));
  845. return oldScale + 0.001 * zoom * (newDistance - oldDistance)
  846. };
  847. function update() {
  848. var self = this;
  849. if (!self.src) {
  850. return
  851. }
  852. self.__oneTouchStart = function(touch) {
  853. self.touchX0 = Math.round(touch.x);
  854. self.touchY0 = Math.round(touch.y);
  855. };
  856. self.__oneTouchMove = function(touch) {
  857. var xMove, yMove;
  858. // 计算单指移动的距离
  859. if (self.touchended) {
  860. return self.updateCanvas()
  861. }
  862. xMove = Math.round(touch.x - self.touchX0);
  863. yMove = Math.round(touch.y - self.touchY0);
  864. var imgLeft = Math.round(self.rectX + xMove);
  865. var imgTop = Math.round(self.rectY + yMove);
  866. self.outsideBound(imgLeft, imgTop);
  867. self.updateCanvas();
  868. };
  869. self.__twoTouchStart = function(touch0, touch1) {
  870. var xMove, yMove, oldDistance;
  871. self.touchX1 = Math.round(self.rectX + self.scaleWidth / 2);
  872. self.touchY1 = Math.round(self.rectY + self.scaleHeight / 2);
  873. // 计算两指距离
  874. xMove = Math.round(touch1.x - touch0.x);
  875. yMove = Math.round(touch1.y - touch0.y);
  876. oldDistance = Math.round(Math.sqrt(xMove * xMove + yMove * yMove));
  877. self.oldDistance = oldDistance;
  878. };
  879. self.__twoTouchMove = function(touch0, touch1) {
  880. var oldScale = self.oldScale;
  881. var oldDistance = self.oldDistance;
  882. var scale = self.scale;
  883. var zoom = self.zoom;
  884. self.newScale = getNewScale(oldScale, oldDistance, zoom, touch0, touch1);
  885. // 设定缩放范围
  886. self.newScale <= 1 && (self.newScale = 1);
  887. self.newScale >= scale && (self.newScale = scale);
  888. self.scaleWidth = Math.round(self.newScale * self.baseWidth);
  889. self.scaleHeight = Math.round(self.newScale * self.baseHeight);
  890. var imgLeft = Math.round(self.touchX1 - self.scaleWidth / 2);
  891. var imgTop = Math.round(self.touchY1 - self.scaleHeight / 2);
  892. self.outsideBound(imgLeft, imgTop);
  893. self.updateCanvas();
  894. };
  895. self.__xtouchEnd = function() {
  896. self.oldScale = self.newScale;
  897. self.rectX = self.imgLeft;
  898. self.rectY = self.imgTop;
  899. };
  900. }
  901. var handle = {
  902. // 图片手势初始监测
  903. touchStart: function touchStart(e) {
  904. var self = this;
  905. var ref = e.touches;
  906. var touch0 = ref[0];
  907. var touch1 = ref[1];
  908. if (!self.src) {
  909. return
  910. }
  911. setTouchState(self, true, null, null);
  912. // 计算第一个触摸点的位置,并参照改点进行缩放
  913. self.__oneTouchStart(touch0);
  914. // 两指手势触发
  915. if (e.touches.length >= 2) {
  916. self.__twoTouchStart(touch0, touch1);
  917. }
  918. },
  919. // 图片手势动态缩放
  920. touchMove: function touchMove(e) {
  921. var self = this;
  922. var ref = e.touches;
  923. var touch0 = ref[0];
  924. var touch1 = ref[1];
  925. if (!self.src) {
  926. return
  927. }
  928. setTouchState(self, null, true);
  929. // 单指手势时触发
  930. if (e.touches.length === 1) {
  931. self.__oneTouchMove(touch0);
  932. }
  933. // 两指手势触发
  934. if (e.touches.length >= 2) {
  935. self.__twoTouchMove(touch0, touch1);
  936. }
  937. },
  938. touchEnd: function touchEnd(e) {
  939. var self = this;
  940. if (!self.src) {
  941. return
  942. }
  943. setTouchState(self, false, false, true);
  944. self.__xtouchEnd();
  945. }
  946. };
  947. function cut() {
  948. var self = this;
  949. var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
  950. var boundHeight = self.height;
  951. // 裁剪框默认高度,即整个画布高度
  952. var ref = self.cut;
  953. var x = ref.x;
  954. if (x === void 0) x = 0;
  955. var y = ref.y;
  956. if (y === void 0) y = 0;
  957. var width = ref.width;
  958. if (width === void 0) width = boundWidth;
  959. var height = ref.height;
  960. if (height === void 0) height = boundHeight;
  961. /**
  962. * 设置边界
  963. * @param imgLeft 图片左上角横坐标值
  964. * @param imgTop 图片左上角纵坐标值
  965. */
  966. self.outsideBound = function(imgLeft, imgTop) {
  967. self.imgLeft = imgLeft >= x ?
  968. x :
  969. self.scaleWidth + imgLeft - x <= width ?
  970. x + width - self.scaleWidth :
  971. imgLeft;
  972. self.imgTop = imgTop >= y ?
  973. y :
  974. self.scaleHeight + imgTop - y <= height ?
  975. y + height - self.scaleHeight :
  976. imgTop;
  977. };
  978. /**
  979. * 设置边界样式
  980. * @param color 边界颜色
  981. */
  982. self.setBoundStyle = function(ref) {
  983. if (ref === void 0) ref = {};
  984. var color = ref.color;
  985. if (color === void 0) color = '#04b00f';
  986. var mask = ref.mask;
  987. if (mask === void 0) mask = 'rgba(0, 0, 0, 0.3)';
  988. var lineWidth = ref.lineWidth;
  989. if (lineWidth === void 0) lineWidth = 1;
  990. var half = lineWidth / 2;
  991. var boundOption = [{
  992. start: {
  993. x: x - half,
  994. y: y + 10 - half
  995. },
  996. step1: {
  997. x: x - half,
  998. y: y - half
  999. },
  1000. step2: {
  1001. x: x + 10 - half,
  1002. y: y - half
  1003. }
  1004. },
  1005. {
  1006. start: {
  1007. x: x - half,
  1008. y: y + height - 10 + half
  1009. },
  1010. step1: {
  1011. x: x - half,
  1012. y: y + height + half
  1013. },
  1014. step2: {
  1015. x: x + 10 - half,
  1016. y: y + height + half
  1017. }
  1018. },
  1019. {
  1020. start: {
  1021. x: x + width - 10 + half,
  1022. y: y - half
  1023. },
  1024. step1: {
  1025. x: x + width + half,
  1026. y: y - half
  1027. },
  1028. step2: {
  1029. x: x + width + half,
  1030. y: y + 10 - half
  1031. }
  1032. },
  1033. {
  1034. start: {
  1035. x: x + width + half,
  1036. y: y + height - 10 + half
  1037. },
  1038. step1: {
  1039. x: x + width + half,
  1040. y: y + height + half
  1041. },
  1042. step2: {
  1043. x: x + width - 10 + half,
  1044. y: y + height + half
  1045. }
  1046. }
  1047. ];
  1048. // 绘制半透明层
  1049. self.ctx.beginPath();
  1050. self.ctx.setFillStyle(mask);
  1051. self.ctx.fillRect(0, 0, x, boundHeight);
  1052. self.ctx.fillRect(x, 0, width, y);
  1053. self.ctx.fillRect(x, y + height, width, boundHeight - y - height);
  1054. self.ctx.fillRect(x + width, 0, boundWidth - x - width, boundHeight);
  1055. self.ctx.fill();
  1056. boundOption.forEach(function(op) {
  1057. self.ctx.beginPath();
  1058. self.ctx.setStrokeStyle(color);
  1059. self.ctx.setLineWidth(lineWidth);
  1060. self.ctx.moveTo(op.start.x, op.start.y);
  1061. self.ctx.lineTo(op.step1.x, op.step1.y);
  1062. self.ctx.lineTo(op.step2.x, op.step2.y);
  1063. self.ctx.stroke();
  1064. });
  1065. };
  1066. }
  1067. var version = "1.3.9";
  1068. var WeCropper = function WeCropper(params) {
  1069. var self = this;
  1070. var _default = {};
  1071. validator(self, DEFAULT);
  1072. Object.keys(DEFAULT).forEach(function(key) {
  1073. _default[key] = DEFAULT[key].default;
  1074. });
  1075. Object.assign(self, _default, params);
  1076. self.prepare();
  1077. self.attachPage();
  1078. self.createCtx();
  1079. self.observer();
  1080. self.cutt();
  1081. self.methods();
  1082. self.init();
  1083. self.update();
  1084. return self
  1085. };
  1086. WeCropper.prototype.init = function init() {
  1087. var self = this;
  1088. var src = self.src;
  1089. self.version = version;
  1090. typeof self.onReady === 'function' && self.onReady(self.ctx, self);
  1091. if (src) {
  1092. self.pushOrign(src);
  1093. } else {
  1094. self.updateCanvas();
  1095. }
  1096. setTouchState(self, false, false, false);
  1097. self.oldScale = 1;
  1098. self.newScale = 1;
  1099. return self
  1100. };
  1101. Object.assign(WeCropper.prototype, handle);
  1102. WeCropper.prototype.prepare = prepare;
  1103. WeCropper.prototype.observer = observer;
  1104. WeCropper.prototype.methods = methods;
  1105. WeCropper.prototype.cutt = cut;
  1106. WeCropper.prototype.update = update;
  1107. return WeCropper;
  1108. })));