weCropper.js 31 KB

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