洛阳学员端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1266 lines
31 KiB

  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. console.log('我的个亲啊')
  721. console.log(src)
  722. tools_7(self.onBeforeImageLoad) && self.onBeforeImageLoad(self.ctx, self);
  723. return getImageInfo({
  724. src: src
  725. })
  726. .then(function(res) {
  727. var innerAspectRadio = res.width / res.height;
  728. var customAspectRadio = width / height;
  729. self.croperTarget = res.path;
  730. if (innerAspectRadio < customAspectRadio) {
  731. self.rectX = x;
  732. self.baseWidth = width;
  733. self.baseHeight = width / innerAspectRadio;
  734. self.rectY = y - Math.abs((height - self.baseHeight) / 2);
  735. } else {
  736. self.rectY = y;
  737. self.baseWidth = height * innerAspectRadio;
  738. self.baseHeight = height;
  739. self.rectX = x - Math.abs((width - self.baseWidth) / 2);
  740. }
  741. self.imgLeft = self.rectX;
  742. self.imgTop = self.rectY;
  743. self.scaleWidth = self.baseWidth;
  744. self.scaleHeight = self.baseHeight;
  745. self.update();
  746. return new Promise(function(resolve) {
  747. self.updateCanvas(resolve);
  748. })
  749. })
  750. .then(function() {
  751. tools_7(self.onImageLoad) && self.onImageLoad(self.ctx, self);
  752. })
  753. };
  754. self.removeImage = function() {
  755. self.src = '';
  756. self.croperTarget = '';
  757. return draw(self.ctx)
  758. };
  759. self.getCropperBase64 = function(done) {
  760. if (done === void 0) done = function() {};
  761. CanvasToBase64.convertToBMP({
  762. canvasId: id,
  763. x: x,
  764. y: y,
  765. width: width,
  766. height: height
  767. }, done);
  768. };
  769. self.getCropperImage = function(opt, fn) {
  770. var customOptions = opt;
  771. var canvasOptions = {
  772. canvasId: id,
  773. x: x,
  774. y: y,
  775. width: width,
  776. height: height
  777. };
  778. var task = function() {
  779. return Promise.resolve();
  780. };
  781. if (
  782. tools_10(customOptions) &&
  783. customOptions.original
  784. ) {
  785. // original mode
  786. task = function() {
  787. self.targetCtx.drawImage(
  788. self.croperTarget,
  789. self.imgLeft * pixelRatio,
  790. self.imgTop * pixelRatio,
  791. self.scaleWidth * pixelRatio,
  792. self.scaleHeight * pixelRatio
  793. );
  794. canvasOptions = {
  795. canvasId: targetId,
  796. x: x * pixelRatio,
  797. y: y * pixelRatio,
  798. width: width * pixelRatio,
  799. height: height * pixelRatio
  800. };
  801. return draw(self.targetCtx)
  802. };
  803. }
  804. return task()
  805. .then(function() {
  806. if (tools_10(customOptions)) {
  807. canvasOptions = Object.assign({}, canvasOptions, customOptions);
  808. }
  809. if (tools_7(customOptions)) {
  810. fn = customOptions;
  811. }
  812. var arg = canvasOptions.componentContext ?
  813. [canvasOptions, canvasOptions.componentContext] :
  814. [canvasOptions];
  815. return canvasToTempFilePath.apply(null, arg)
  816. })
  817. .then(function(res) {
  818. var tempFilePath = res.tempFilePath;
  819. return tools_7(fn) ?
  820. fn.call(self, tempFilePath, null) :
  821. tempFilePath
  822. })
  823. .catch(function(err) {
  824. if (tools_7(fn)) {
  825. fn.call(self, null, err);
  826. } else {
  827. throw err
  828. }
  829. })
  830. };
  831. }
  832. /**
  833. * 获取最新缩放值
  834. * @param oldScale 上一次触摸结束后的缩放值
  835. * @param oldDistance 上一次触摸结束后的双指距离
  836. * @param zoom 缩放系数
  837. * @param touch0 第一指touch对象
  838. * @param touch1 第二指touch对象
  839. * @returns {*}
  840. */
  841. var getNewScale = function(oldScale, oldDistance, zoom, touch0, touch1) {
  842. var xMove, yMove, newDistance;
  843. // 计算二指最新距离
  844. xMove = Math.round(touch1.x - touch0.x);
  845. yMove = Math.round(touch1.y - touch0.y);
  846. newDistance = Math.round(Math.sqrt(xMove * xMove + yMove * yMove));
  847. return oldScale + 0.001 * zoom * (newDistance - oldDistance)
  848. };
  849. function update() {
  850. var self = this;
  851. if (!self.src) {
  852. return
  853. }
  854. self.__oneTouchStart = function(touch) {
  855. self.touchX0 = Math.round(touch.x);
  856. self.touchY0 = Math.round(touch.y);
  857. };
  858. self.__oneTouchMove = function(touch) {
  859. var xMove, yMove;
  860. // 计算单指移动的距离
  861. if (self.touchended) {
  862. return self.updateCanvas()
  863. }
  864. xMove = Math.round(touch.x - self.touchX0);
  865. yMove = Math.round(touch.y - self.touchY0);
  866. var imgLeft = Math.round(self.rectX + xMove);
  867. var imgTop = Math.round(self.rectY + yMove);
  868. self.outsideBound(imgLeft, imgTop);
  869. self.updateCanvas();
  870. };
  871. self.__twoTouchStart = function(touch0, touch1) {
  872. var xMove, yMove, oldDistance;
  873. self.touchX1 = Math.round(self.rectX + self.scaleWidth / 2);
  874. self.touchY1 = Math.round(self.rectY + self.scaleHeight / 2);
  875. // 计算两指距离
  876. xMove = Math.round(touch1.x - touch0.x);
  877. yMove = Math.round(touch1.y - touch0.y);
  878. oldDistance = Math.round(Math.sqrt(xMove * xMove + yMove * yMove));
  879. self.oldDistance = oldDistance;
  880. };
  881. self.__twoTouchMove = function(touch0, touch1) {
  882. var oldScale = self.oldScale;
  883. var oldDistance = self.oldDistance;
  884. var scale = self.scale;
  885. var zoom = self.zoom;
  886. self.newScale = getNewScale(oldScale, oldDistance, zoom, touch0, touch1);
  887. // 设定缩放范围
  888. self.newScale <= 1 && (self.newScale = 1);
  889. self.newScale >= scale && (self.newScale = scale);
  890. self.scaleWidth = Math.round(self.newScale * self.baseWidth);
  891. self.scaleHeight = Math.round(self.newScale * self.baseHeight);
  892. var imgLeft = Math.round(self.touchX1 - self.scaleWidth / 2);
  893. var imgTop = Math.round(self.touchY1 - self.scaleHeight / 2);
  894. self.outsideBound(imgLeft, imgTop);
  895. self.updateCanvas();
  896. };
  897. self.__xtouchEnd = function() {
  898. self.oldScale = self.newScale;
  899. self.rectX = self.imgLeft;
  900. self.rectY = self.imgTop;
  901. };
  902. }
  903. var handle = {
  904. // 图片手势初始监测
  905. touchStart: function touchStart(e) {
  906. var self = this;
  907. var ref = e.touches;
  908. var touch0 = ref[0];
  909. var touch1 = ref[1];
  910. if (!self.src) {
  911. return
  912. }
  913. setTouchState(self, true, null, null);
  914. // 计算第一个触摸点的位置,并参照改点进行缩放
  915. self.__oneTouchStart(touch0);
  916. // 两指手势触发
  917. if (e.touches.length >= 2) {
  918. self.__twoTouchStart(touch0, touch1);
  919. }
  920. },
  921. // 图片手势动态缩放
  922. touchMove: function touchMove(e) {
  923. var self = this;
  924. var ref = e.touches;
  925. var touch0 = ref[0];
  926. var touch1 = ref[1];
  927. if (!self.src) {
  928. return
  929. }
  930. setTouchState(self, null, true);
  931. // 单指手势时触发
  932. if (e.touches.length === 1) {
  933. self.__oneTouchMove(touch0);
  934. }
  935. // 两指手势触发
  936. if (e.touches.length >= 2) {
  937. self.__twoTouchMove(touch0, touch1);
  938. }
  939. },
  940. touchEnd: function touchEnd(e) {
  941. var self = this;
  942. if (!self.src) {
  943. return
  944. }
  945. setTouchState(self, false, false, true);
  946. self.__xtouchEnd();
  947. }
  948. };
  949. function cut() {
  950. var self = this;
  951. var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
  952. var boundHeight = self.height;
  953. // 裁剪框默认高度,即整个画布高度
  954. var ref = self.cut;
  955. var x = ref.x;
  956. if (x === void 0) x = 0;
  957. var y = ref.y;
  958. if (y === void 0) y = 0;
  959. var width = ref.width;
  960. if (width === void 0) width = boundWidth;
  961. var height = ref.height;
  962. if (height === void 0) height = boundHeight;
  963. /**
  964. * 设置边界
  965. * @param imgLeft 图片左上角横坐标值
  966. * @param imgTop 图片左上角纵坐标值
  967. */
  968. self.outsideBound = function(imgLeft, imgTop) {
  969. self.imgLeft = imgLeft >= x ?
  970. x :
  971. self.scaleWidth + imgLeft - x <= width ?
  972. x + width - self.scaleWidth :
  973. imgLeft;
  974. self.imgTop = imgTop >= y ?
  975. y :
  976. self.scaleHeight + imgTop - y <= height ?
  977. y + height - self.scaleHeight :
  978. imgTop;
  979. };
  980. /**
  981. * 设置边界样式
  982. * @param color 边界颜色
  983. */
  984. self.setBoundStyle = function(ref) {
  985. if (ref === void 0) ref = {};
  986. var color = ref.color;
  987. if (color === void 0) color = '#04b00f';
  988. var mask = ref.mask;
  989. if (mask === void 0) mask = 'rgba(0, 0, 0, 0.3)';
  990. var lineWidth = ref.lineWidth;
  991. if (lineWidth === void 0) lineWidth = 1;
  992. var half = lineWidth / 2;
  993. var boundOption = [{
  994. start: {
  995. x: x - half,
  996. y: y + 10 - half
  997. },
  998. step1: {
  999. x: x - half,
  1000. y: y - half
  1001. },
  1002. step2: {
  1003. x: x + 10 - half,
  1004. y: y - half
  1005. }
  1006. },
  1007. {
  1008. start: {
  1009. x: x - half,
  1010. y: y + height - 10 + half
  1011. },
  1012. step1: {
  1013. x: x - half,
  1014. y: y + height + half
  1015. },
  1016. step2: {
  1017. x: x + 10 - half,
  1018. y: y + height + half
  1019. }
  1020. },
  1021. {
  1022. start: {
  1023. x: x + width - 10 + half,
  1024. y: y - half
  1025. },
  1026. step1: {
  1027. x: x + width + half,
  1028. y: y - half
  1029. },
  1030. step2: {
  1031. x: x + width + half,
  1032. y: y + 10 - half
  1033. }
  1034. },
  1035. {
  1036. start: {
  1037. x: x + width + half,
  1038. y: y + height - 10 + half
  1039. },
  1040. step1: {
  1041. x: x + width + half,
  1042. y: y + height + half
  1043. },
  1044. step2: {
  1045. x: x + width - 10 + half,
  1046. y: y + height + half
  1047. }
  1048. }
  1049. ];
  1050. // 绘制半透明层
  1051. self.ctx.beginPath();
  1052. self.ctx.setFillStyle(mask);
  1053. self.ctx.fillRect(0, 0, x, boundHeight);
  1054. self.ctx.fillRect(x, 0, width, y);
  1055. self.ctx.fillRect(x, y + height, width, boundHeight - y - height);
  1056. self.ctx.fillRect(x + width, 0, boundWidth - x - width, boundHeight);
  1057. self.ctx.fill();
  1058. boundOption.forEach(function(op) {
  1059. self.ctx.beginPath();
  1060. self.ctx.setStrokeStyle(color);
  1061. self.ctx.setLineWidth(lineWidth);
  1062. self.ctx.moveTo(op.start.x, op.start.y);
  1063. self.ctx.lineTo(op.step1.x, op.step1.y);
  1064. self.ctx.lineTo(op.step2.x, op.step2.y);
  1065. self.ctx.stroke();
  1066. });
  1067. };
  1068. }
  1069. var version = "1.3.9";
  1070. var WeCropper = function WeCropper(params) {
  1071. var self = this;
  1072. var _default = {};
  1073. validator(self, DEFAULT);
  1074. Object.keys(DEFAULT).forEach(function(key) {
  1075. _default[key] = DEFAULT[key].default;
  1076. });
  1077. Object.assign(self, _default, params);
  1078. self.prepare();
  1079. self.attachPage();
  1080. self.createCtx();
  1081. self.observer();
  1082. self.cutt();
  1083. self.methods();
  1084. self.init();
  1085. self.update();
  1086. return self
  1087. };
  1088. WeCropper.prototype.init = function init() {
  1089. var self = this;
  1090. var src = self.src;
  1091. self.version = version;
  1092. typeof self.onReady === 'function' && self.onReady(self.ctx, self);
  1093. if (src) {
  1094. self.pushOrign(src);
  1095. } else {
  1096. self.updateCanvas();
  1097. }
  1098. setTouchState(self, false, false, false);
  1099. self.oldScale = 1;
  1100. self.newScale = 1;
  1101. return self
  1102. };
  1103. Object.assign(WeCropper.prototype, handle);
  1104. WeCropper.prototype.prepare = prepare;
  1105. WeCropper.prototype.observer = observer;
  1106. WeCropper.prototype.methods = methods;
  1107. WeCropper.prototype.cutt = cut;
  1108. WeCropper.prototype.update = update;
  1109. return WeCropper;
  1110. })));