qf-image-cropper.render.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /**
  2. * 图片编辑器-手势监听
  3. * 1. 支持编译到app-vue(uni-app 2.5.5及以上版本)、H5上
  4. */
  5. /** 图片偏移量 */
  6. var offset = { x: 0, y: 0 };
  7. /** 图片缩放比例 */
  8. var scale = 1;
  9. /** 图片最小缩放比例 */
  10. var minScale = 1;
  11. /** 图片旋转角度 */
  12. var rotate = 0;
  13. /** 触摸点 */
  14. var touches = [];
  15. /** 图片布局信息 */
  16. var img = {};
  17. /** 系统信息 */
  18. var sys = {};
  19. /** 裁剪区域布局信息 */
  20. var area = {};
  21. /** 触摸行为类型 */
  22. var touchType = '';
  23. /** 操作角的位置 */
  24. var activeAngle = 0;
  25. /** 裁剪区域布局信息偏移量 */
  26. var areaOffset = { left: 0, right: 0, top: 0, bottom: 0 };
  27. /** 元素ID */
  28. var elIds = {
  29. 'imageStyles': 'crop-image',
  30. 'maskStylesList': 'crop-mask-block',
  31. 'borderStyles': 'crop-border',
  32. 'circleBoxStyles': 'crop-circle-box',
  33. 'circleStyles': 'crop-circle',
  34. 'gridStylesList': 'crop-grid',
  35. 'angleStylesList': 'crop-angle',
  36. }
  37. /** 记录上次初始化时间戳,排除APP重复更新 */
  38. var timestamp = 0;
  39. /** vue3 renderjs 条件编译无效,以此方式区别 APP 和 H5 */
  40. // #ifdef H5
  41. var platform = 'H5';
  42. // #endif
  43. // #ifdef APP
  44. var platform = 'APP';
  45. // #endif
  46. /** 容错值 */
  47. var fault = 0.000001;
  48. /**
  49. * 获取a、b两数中的最小正数
  50. * @param a
  51. * @param b
  52. */
  53. function minimum(a, b) {
  54. if (a > 0 && b < 0) return a;
  55. if (a < 0 && b > 0) return b;
  56. if (a > 0 && b > 0) return Math.min(a, b);
  57. return 0;
  58. }
  59. /**
  60. * 在容错访问内获取n近似值
  61. * @param n
  62. */
  63. function num(n) {
  64. var m = parseFloat((n).toFixed(6));
  65. return m === fault || m === -fault ? 0 : m;
  66. }
  67. /**
  68. * 比较a值在容错值范围内是否等于b值
  69. * @param a
  70. * @param b
  71. */
  72. function equalsByFault(a, b) {
  73. return Math.abs(a - b) <= fault;
  74. }
  75. /**
  76. * 比较a值在容错值范围内是否小于b值
  77. * @param a
  78. * @param b
  79. */
  80. function lessThanByFault(a, b) {
  81. var c = a - b;
  82. return c < 0 ? c < -fault : c < fault;
  83. }
  84. /**
  85. * 验证并获取有效最大值
  86. * @param v
  87. * @param max
  88. * @param isInclude
  89. * @param x
  90. * @param y
  91. * @param rate
  92. * @returns
  93. */
  94. function validMax(v, max, isInclude, x, y, rate) {
  95. if(typeof max === 'number') {
  96. if(isInclude && equalsByFault(max, y)) { // 宽高不等时,x轴用y轴值要做等比例转换
  97. var n = num(max * rate);
  98. if (n <= x) return n; // 转化后值在x轴最大值范围内
  99. return x; // 转化后值超出x轴最大值范围则用最大值
  100. }
  101. return max;
  102. }
  103. return v;
  104. }
  105. /**
  106. * 样式对象转字符串
  107. * @param {Object} style 样式对象
  108. */
  109. function styleToString(style) {
  110. if(typeof style === 'string') return style;
  111. var str = '';
  112. for (let k in style) {
  113. str += k + ':' + style[k] + ';';
  114. }
  115. return str;
  116. }
  117. /**
  118. *
  119. * @param {Object} instance 页面实例对象
  120. * @param {Object} key 要修改样式的key
  121. * @param {Object|Array} style 样式
  122. */
  123. function setStyle(instance, key, style) {
  124. // console.log('setStyle', instance, key, JSON.stringify(style))
  125. // #ifdef APP-PLUS
  126. if(platform === 'APP') {
  127. if(Object.prototype.toString.call(style) === '[object Array]') {
  128. for (var i = 0, len = style.length; i < len; i++) {
  129. var el = window.document.getElementById(elIds[key] + '-' + (i + 1));
  130. el && (el.style = styleToString(style[i]));
  131. }
  132. } else {
  133. var el = window.document.getElementById(elIds[key]);
  134. el && (el.style = styleToString(style));
  135. }
  136. }
  137. // #endif
  138. // #ifdef H5
  139. if(platform === 'H5') instance[key] = style;
  140. // #endif
  141. }
  142. /**
  143. * 触发页面实例指定方法
  144. * @param {Object} instance 页面实例对象
  145. * @param {Object} name 方法名称
  146. * @param {Object} obj 传递参数
  147. */
  148. function callMethod(instance, name, obj) {
  149. // #ifdef APP-PLUS
  150. if(platform === 'APP') instance.callMethod(name, obj);
  151. // #endif
  152. // #ifdef H5
  153. if(platform === 'H5') instance[name](obj);
  154. // #endif
  155. }
  156. /**
  157. * 计算两点间距
  158. * @param {Object} touches 触摸点信息
  159. */
  160. function getDistanceByTouches(touches) {
  161. // 根据勾股定理求两点间距离
  162. var a = touches[1].pageX - touches[0].pageX;
  163. var b = touches[1].pageY - touches[0].pageY;
  164. var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
  165. // 求两点间的中点坐标
  166. // 1. a、b可能为负值
  167. // 2. 在求a、b时,如用touches[1]减touches[0],则求中点坐标也得用touches[1]减a/2、b/2
  168. // 3. 同理,在求a、b时,也可用touches[0]减touches[1],则求中点坐标也得用touches[0]减a/2、b/2
  169. var x = touches[1].pageX - a / 2;
  170. var y = touches[1].pageY - b / 2;
  171. return { c, x, y };
  172. };
  173. /**
  174. * 修正取值
  175. * @param {Object} a
  176. * @param {Object} b
  177. * @param {Object} c
  178. * @param {Object} reverse 是否反向
  179. */
  180. function correctValue(a, b, c, reverse) {
  181. return num(reverse ? Math.max(Math.min(a, b), c) : Math.min(Math.max(a, b), c));
  182. }
  183. /**
  184. * 旋转90°或270°时检查边界:限制 x、y 拖动范围,禁止滑出边界
  185. * @param {Object} e 点坐标
  186. * @param {Object} xReverse x是否反向
  187. * @param {Object} yReverse y是否反向
  188. */
  189. function checkRotateRange(e, xReverse, yReverse) {
  190. var o = num((img.height - img.width) / 2); // 宽高差值一半
  191. return {
  192. x: correctValue(e.x, -img.height + o + area.width + area.left, area.left + o, xReverse),
  193. y: correctValue(e.y, -img.width - o + area.height + area.top, area.top - o, yReverse)
  194. };
  195. }
  196. /**
  197. * 检查边界:限制 x、y 拖动范围,禁止滑出边界
  198. * @param {Object} e 点坐标
  199. */
  200. function checkRange(e) {
  201. var r = rotate / 90 % 2;
  202. if(r === 1) { // 因图片宽高可能不等,翻转 90° 或 270° 后图片宽高需反着计算,且左右和上下边界要根据差值做偏移
  203. if (area.width === area.height) {
  204. return checkRotateRange(e, img.height < area.height, img.width < area.width);
  205. }
  206. var isInclude = img.height < area.width && img.width < area.height; // 图片是否包含在裁剪区域内
  207. if (img.width < area.height || img.height < area.width) {
  208. if (area.width < area.height && img.width < img.height) {
  209. return isInclude
  210. ? checkRotateRange(e, area.width < area.height, area.width < area.height)
  211. : checkRotateRange(e, false, true);
  212. }
  213. if (area.height < area.width && img.height < img.width) {
  214. return isInclude
  215. ? checkRotateRange(e, area.height < area.width, area.height < area.width)
  216. : checkRotateRange(e, true, false);
  217. }
  218. }
  219. if (img.height >= area.width && img.width >= area.height) {
  220. return checkRotateRange(e, false, false);
  221. }
  222. if (isInclude) {
  223. return area.height < area.width
  224. ? checkRotateRange(e, true, true)
  225. : checkRotateRange(e, area.width < area.height, area.width < area.height);
  226. }
  227. if (img.height < area.width && !img.width < area.height) {
  228. return checkRotateRange(e, true, false);
  229. }
  230. if (!img.height < area.width && img.width < area.height) {
  231. return checkRotateRange(e, false, true);
  232. }
  233. return checkRotateRange(e, img.height < area.height, img.width < area.width);
  234. }
  235. return {
  236. x: correctValue(e.x, -img.width + area.width + area.left, area.left, img.width < area.width),
  237. y: correctValue(e.y, -img.height + area.height + area.top, area.top, img.height < area.height)
  238. }
  239. };
  240. /**
  241. * 变更图片布局信息
  242. * @param {Object} e 布局信息
  243. */
  244. function changeImageRect(e) {
  245. // console.log('changeImageRect', e)
  246. offset.x += e.x || 0;
  247. offset.y += e.y || 0;
  248. if(e.check && area.checkRange) { // 检查边界
  249. var point = checkRange(offset);
  250. if(offset.x !== point.x || offset.y !== point.y) {
  251. offset = point;
  252. }
  253. }
  254. // 因频繁修改 width/height 会造成大量的内存消耗,改为scale
  255. // e.instance.imageStyles = {
  256. // width: img.width + 'px',
  257. // height: img.height + 'px',
  258. // transform: 'translate(' + (offset.x + ox) + 'px, ' + (offset.y + ox) + 'px) rotate(' + rotate +'deg)'
  259. // };
  260. var ox = (img.width - img.oldWidth) / 2;
  261. var oy = (img.height - img.oldHeight) / 2;
  262. // e.instance.imageStyles = {
  263. // width: img.oldWidth + 'px',
  264. // height: img.oldHeight + 'px',
  265. // transform: 'translate(' + (offset.x + ox) + 'px, ' + (offset.y + oy) + 'px) rotate(' + rotate +'deg) scale(' + scale + ')'
  266. // };
  267. setStyle(e.instance, 'imageStyles', {
  268. width: img.oldWidth + 'px',
  269. height: img.oldHeight + 'px',
  270. transform: (img.gpu ? 'translateZ(0) ' : '') + 'translate(' + (offset.x + ox) + 'px, ' + (offset.y + oy) + 'px' + ') rotate(' + rotate +'deg) scale(' + scale + ')'
  271. });
  272. callMethod(e.instance, 'dataChange', {
  273. width: img.width,
  274. height: img.height,
  275. x: offset.x,
  276. y: offset.y,
  277. rotate: rotate
  278. });
  279. };
  280. /**
  281. * 变更裁剪区域布局信息
  282. * @param {Object} e 布局信息
  283. */
  284. function changeAreaRect(e) {
  285. // console.log('changeAreaRect', e)
  286. // 变更蒙版样式
  287. setStyle(e.instance, 'maskStylesList', [
  288. {
  289. left: 0,
  290. width: (area.left + areaOffset.left) + 'px',
  291. top: 0,
  292. bottom: 0,
  293. 'z-index': area.zIndex + 2
  294. },
  295. {
  296. left: (area.right + areaOffset.right) + 'px',
  297. right: 0,
  298. top: 0,
  299. bottom: 0,
  300. 'z-index': area.zIndex + 2
  301. },
  302. {
  303. left: (area.left + areaOffset.left) + 'px',
  304. width: (area.width + areaOffset.right - areaOffset.left) + 'px',
  305. top: 0,
  306. height: (area.top + areaOffset.top) + 'px',
  307. 'z-index': area.zIndex + 2
  308. },
  309. {
  310. left: (area.left + areaOffset.left) + 'px',
  311. width: (area.width + areaOffset.right - areaOffset.left) + 'px',
  312. top: (area.bottom + areaOffset.bottom) + 'px',
  313. // height: (area.top - areaOffset.bottom + sys.offsetBottom) + 'px',
  314. bottom: 0,
  315. 'z-index': area.zIndex + 2
  316. }
  317. ]);
  318. // 变更边框样式
  319. if(area.showBorder) {
  320. setStyle(e.instance, 'borderStyles', {
  321. left: (area.left + areaOffset.left) + 'px',
  322. top: (area.top + areaOffset.top) + 'px',
  323. width: (area.width + areaOffset.right - areaOffset.left) + 'px',
  324. height: (area.height + areaOffset.bottom - areaOffset.top) + 'px',
  325. 'z-index': area.zIndex + 3
  326. });
  327. }
  328. // 变更参考线样式
  329. if(area.showGrid) {
  330. setStyle(e.instance, 'gridStylesList', [
  331. {
  332. 'border-width': '1px 0 0 0',
  333. left: (area.left + areaOffset.left) + 'px',
  334. right: (area.right + areaOffset.right) + 'px',
  335. top: (area.top + areaOffset.top + (area.height + areaOffset.bottom - areaOffset.top) / 3 - 0.5) + 'px',
  336. width: (area.width + areaOffset.right - areaOffset.left) + 'px',
  337. 'z-index': area.zIndex + 3
  338. },
  339. {
  340. 'border-width': '1px 0 0 0',
  341. left: (area.left + areaOffset.left) + 'px',
  342. right: (area.right + areaOffset.right) + 'px',
  343. top: (area.top + areaOffset.top + (area.height + areaOffset.bottom - areaOffset.top) * 2 / 3 - 0.5) + 'px',
  344. width: (area.width + areaOffset.right - areaOffset.left) + 'px',
  345. 'z-index': area.zIndex + 3
  346. },
  347. {
  348. 'border-width': '0 1px 0 0',
  349. top: (area.top + areaOffset.top) + 'px',
  350. bottom: (area.bottom + areaOffset.bottom) + 'px',
  351. left: (area.left + areaOffset.left + (area.width + areaOffset.right - areaOffset.left) / 3 - 0.5) + 'px',
  352. height: (area.height + areaOffset.bottom - areaOffset.top) + 'px',
  353. 'z-index': area.zIndex + 3
  354. },
  355. {
  356. 'border-width': '0 1px 0 0',
  357. top: (area.top + areaOffset.top) + 'px',
  358. bottom: (area.bottom + areaOffset.bottom) + 'px',
  359. left: (area.left + areaOffset.left + (area.width + areaOffset.right - areaOffset.left) * 2 / 3 - 0.5) + 'px',
  360. height: (area.height + areaOffset.bottom - areaOffset.top) + 'px',
  361. 'z-index': area.zIndex + 3
  362. }
  363. ]);
  364. }
  365. // 变更四个伸缩角样式
  366. if(area.showAngle) {
  367. setStyle(e.instance, 'angleStylesList', [
  368. {
  369. 'border-width': area.angleBorderWidth + 'px 0 0 ' + area.angleBorderWidth + 'px',
  370. left: (area.left + areaOffset.left - area.angleBorderWidth) + 'px',
  371. top: (area.top + areaOffset.top - area.angleBorderWidth) + 'px',
  372. 'z-index': area.zIndex + 3
  373. },
  374. {
  375. 'border-width': area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px 0 0',
  376. left: (area.right + areaOffset.right - area.angleSize) + 'px',
  377. top: (area.top + areaOffset.top - area.angleBorderWidth) + 'px',
  378. 'z-index': area.zIndex + 3
  379. },
  380. {
  381. 'border-width': '0 0 ' + area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px',
  382. left: (area.left + areaOffset.left - area.angleBorderWidth) + 'px',
  383. top: (area.bottom + areaOffset.bottom - area.angleSize) + 'px',
  384. 'z-index': area.zIndex + 3
  385. },
  386. {
  387. 'border-width': '0 ' + area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px 0',
  388. left: (area.right + areaOffset.right - area.angleSize) + 'px',
  389. top: (area.bottom + areaOffset.bottom - area.angleSize) + 'px',
  390. 'z-index': area.zIndex + 3
  391. }
  392. ]);
  393. }
  394. // 变更圆角样式
  395. if(area.radius > 0) {
  396. var radius = area.radius;
  397. if(area.width === area.height && area.radius >= area.width / 2) { // 圆形
  398. radius = (area.width / 2);
  399. } else { // 圆角矩形
  400. if(area.width !== area.height) { // 限制圆角半径不能超过短边的一半
  401. radius = Math.min(area.width / 2, area.height / 2, radius);
  402. }
  403. }
  404. setStyle(e.instance, 'circleBoxStyles', {
  405. left: (area.left + areaOffset.left) + 'px',
  406. top: (area.top + areaOffset.top) + 'px',
  407. width: (area.width + areaOffset.right - areaOffset.left) + 'px',
  408. height: (area.height + areaOffset.bottom - areaOffset.top) + 'px',
  409. 'z-index': area.zIndex + 2
  410. });
  411. setStyle(e.instance, 'circleStyles', {
  412. 'box-shadow': '0 0 0 ' + Math.max(area.width, area.height) + 'px rgba(51, 51, 51, 0.8)',
  413. 'border-radius': radius + 'px'
  414. });
  415. }
  416. };
  417. /**
  418. * 缩放图片
  419. * @param {Object} e 布局信息
  420. */
  421. function scaleImage(e) {
  422. // console.log('scaleImage', e)
  423. var last = scale;
  424. scale = Math.min(Math.max(e.scale + scale, minScale), img.maxScale);
  425. if(last !== scale) {
  426. img.width = num(img.oldWidth * scale);
  427. img.height = num(img.oldHeight * scale);
  428. // 参考问题:有一个长4000px、宽4000px的四方形ABCD,A点的坐标固定在(-2000,-2000),
  429. // 该四边形上有一个点E,坐标为(-100,-300),将该四方形复制一份并缩小到90%后,
  430. // 新四边形的A点坐标为多少时可使新四边形的E点与原四边形的E点重合?
  431. // 预期效果:从图中选取某点(参照物)为中心点进行缩放,缩放时无论图像怎么变化,该点位置始终固定不变
  432. // 计算方法:以相同起点先计算缩放前后两点间的距离,再加上原图像偏移量即可
  433. e.x = num((e.x - offset.x) * (1 - scale / last));
  434. e.y = num((e.y - offset.y) * (1 - scale / last));
  435. changeImageRect(e);
  436. return true;
  437. }
  438. return false;
  439. };
  440. /**
  441. * 获取触摸点在哪个角
  442. * @param {number} x 触摸点x轴坐标
  443. * @param {number} y 触摸点y轴坐标
  444. * @return {number} 角的位置:0=无;1=左上;2=右上;3=左下;4=右下;
  445. */
  446. function getToucheAngle(x, y) {
  447. // console.log('getToucheAngle', x, y, JSON.stringify(area))
  448. var o = area.angleBorderWidth; // 需扩大触发范围则把 o 值加大即可
  449. var oy = sys.navigation ? 0 : sys.windowTop;
  450. if(y >= area.top - o + oy && y <= area.top + area.angleSize + o + oy) {
  451. if(x >= area.left - o && x <= area.left + area.angleSize + o) {
  452. return 1; // 左上角
  453. } else if(x >= area.right - area.angleSize - o && x <= area.right + o) {
  454. return 2; // 右上角
  455. }
  456. } else if(y >= area.bottom - area.angleSize - o + oy && y <= area.bottom + o + oy) {
  457. if(x >= area.left - o && x <= area.left + area.angleSize + o) {
  458. return 3; // 左下角
  459. } else if(x >= area.right - area.angleSize - o && x <= area.right + o) {
  460. return 4; // 右下角
  461. }
  462. }
  463. return 0; // 无触摸到角
  464. };
  465. /**
  466. * 重置数据
  467. */
  468. function resetData() {
  469. offset = { x: 0, y: 0 };
  470. scale = 1;
  471. minScale = img.minScale;
  472. rotate = 0;
  473. };
  474. function getTouchs(touches) {
  475. var result = [];
  476. var len = touches ? touches.length : 0
  477. for (var i = 0; i < len; i++) {
  478. result[i] = {
  479. pageX: touches[i].pageX,
  480. // h5无标题栏时,窗口顶部距离仍为标题栏高度,且触摸点y轴坐标还是有标题栏的值,即减去标题栏高度的值
  481. pageY: touches[i].pageY + sys.windowTop
  482. };
  483. }
  484. return result;
  485. };
  486. var mouseEvent = false;
  487. export default {
  488. data() {
  489. return {
  490. imageStyles: {},
  491. maskStylesList: [{}, {}, {}, {}],
  492. borderStyles: {},
  493. gridStylesList: [{}, {}, {}, {}],
  494. angleStylesList: [{}, {}, {}, {}],
  495. circleBoxStyles: {},
  496. circleStyles: {}
  497. }
  498. },
  499. created() {
  500. // 监听 PC 端鼠标滚轮
  501. // #ifdef H5
  502. platform === 'H5' && window.addEventListener('mousewheel', async (e) => {
  503. var touchs = getTouchs([e])
  504. img.src && scaleImage({
  505. instance: await this.getInstance(),
  506. check: true,
  507. // 鼠标向上滚动时,deltaY 固定 -100,鼠标向下滚动时,deltaY 固定 100
  508. scale: e.deltaY > 0 ? -0.05 : 0.05,
  509. x: touchs[0].pageX,
  510. y: touchs[0].pageY
  511. });
  512. });
  513. // #endif
  514. },
  515. // #ifdef H5
  516. mounted() {
  517. platform === 'H5' && this.initH5Events();
  518. },
  519. // #endif
  520. setPlatform(p) {
  521. platform = p;
  522. },
  523. methods: {
  524. // #ifdef H5
  525. getTouchEvent(e) {
  526. e.touches = [
  527. { pageX: e.pageX, pageY: e.pageY }
  528. ];
  529. return e;
  530. },
  531. initH5Events() {
  532. const preview = document.getElementById('pic-preview');
  533. preview?.addEventListener('mousedown', (e, ev) => {
  534. mouseEvent = true;
  535. this.touchstart(this.getTouchEvent(e));
  536. });
  537. preview?.addEventListener('mousemove', (e) => {
  538. if (!mouseEvent) return;
  539. this.touchmove(this.getTouchEvent(e));
  540. });
  541. preview?.addEventListener('mouseup', (e) => {
  542. mouseEvent = false;
  543. this.touchend(this.getTouchEvent(e))
  544. });
  545. preview?.addEventListener('mouseleave', (e) => {
  546. mouseEvent = false;
  547. this.touchend(this.getTouchEvent(e))
  548. });
  549. },
  550. // #endif
  551. async getInstance() {
  552. // #ifdef APP-PLUS
  553. if(platform === 'APP')
  554. return this.$ownerInstance
  555. ? Promise.resolve(this.$ownerInstance)
  556. : new Promise((resolve) => {
  557. setTimeout(async () => {
  558. resolve(await this.getInstance());
  559. });
  560. });
  561. // #endif
  562. // #ifdef H5
  563. if(platform === 'H5')
  564. return Promise.resolve(this);
  565. // #endif
  566. },
  567. /**
  568. * 初始化:观察数据变更
  569. * @param {Object} newVal 新数据
  570. * @param {Object} oldVal 旧数据
  571. * @param {Object} o 组件实例对象
  572. */
  573. initObserver: async function(newVal, oldVal, o, i) {
  574. // console.log('initObserver', newVal, oldVal, o, i)
  575. if(newVal && (!img.src || timestamp !== newVal.timestamp)) {
  576. timestamp = newVal.timestamp;
  577. img = newVal.img;
  578. sys = newVal.sys;
  579. area = newVal.area;
  580. minScale = img.minScale;
  581. resetData();
  582. const instance = await this.getInstance()
  583. img.src && changeImageRect({
  584. instance,
  585. x: (sys.windowWidth - img.width) / 2,
  586. y: (sys.windowHeight + sys.windowTop - sys.offsetBottom - img.height) / 2
  587. });
  588. changeAreaRect({
  589. instance
  590. });
  591. }
  592. },
  593. /**
  594. * 鼠标滚轮滚动
  595. * @param {Object} e 事件对象
  596. * @param {Object} o 组件实例对象
  597. */
  598. mousewheel: function(e, o) {
  599. // h5平台 wheel 事件无法判断滚轮滑动方向,需使用 mousewheel
  600. },
  601. /**
  602. * 触摸开始
  603. * @param {Object} e 事件对象
  604. * @param {Object} o 组件实例对象
  605. */
  606. touchstart: function(e, o) {
  607. if(!img.src) return;
  608. touches = getTouchs(e.touches);
  609. activeAngle = area.showAngle ? getToucheAngle(touches[0].pageX, touches[0].pageY) : 0;
  610. if(touches.length === 1 && activeAngle !== 0) {
  611. touchType = 'stretch'; // 伸缩裁剪区域
  612. } else {
  613. touchType = '';
  614. }
  615. // console.log('touchstart', e, activeAngle)
  616. },
  617. /**
  618. * 触摸移动
  619. * @param {Object} e 事件对象
  620. * @param {Object} o 组件实例对象
  621. */
  622. touchmove: async function(e, o) {
  623. if(!img.src) return;
  624. // console.log('touchmove', e, o)
  625. e.touches = getTouchs(e.touches);
  626. if(touchType === 'stretch') { // 触摸四个角进行拉伸
  627. var point = e.touches[0];
  628. var start = touches[0];
  629. var x = point.pageX - start.pageX;
  630. var y = point.pageY - start.pageY;
  631. if(x !== 0 || y !== 0) {
  632. var maxX = num(area.width * (1 - area.minScale));
  633. var maxY = num(area.height * (1 - area.minScale));
  634. // console.log(x, y, maxX, maxY, offset, area)
  635. touches[0] = point;
  636. var r = rotate / 90 % 2;
  637. var m = r === 1 ? num((img.height - img.width) / 2) : 0; // 宽高差值一半
  638. var xCompare = r === 1 ? lessThanByFault(img.height, area.width) : lessThanByFault(img.width, area.width);
  639. var yCompare = r === 1 ? lessThanByFault(img.width, area.height) : lessThanByFault(img.height, area.height)
  640. var isInclude = xCompare && yCompare;
  641. var isIntersect = area.checkRange && (xCompare || yCompare); // 图片是否包含在裁剪区域内
  642. var isReverse = !isInclude || num((offset.x - area.left) / area.width) <= num((offset.y - area.top) / area.height) || (area.width > area.height && img.width < img.height && r === 1);
  643. switch(activeAngle) {
  644. case 1: // 左上角
  645. x = num(x + areaOffset.left);
  646. y = num(y + areaOffset.top);
  647. if(x >= 0 && y >= 0) { // 有效滑动
  648. var t = num(offset.y + m - area.top);
  649. var l = num(offset.x - m - area.left);
  650. // && (offset.x + img.width < area.right || offset.y + img.height < area.bottom)
  651. var max = isIntersect && ((l >= 0) || (t >= 0))
  652. ? minimum(t, l)
  653. : false;
  654. if(x > y && isReverse) { // 以x轴滑动距离为缩放基准
  655. maxX = validMax(maxX, max, isInclude, l, t, area.width / area.height);
  656. if(x > maxX) x = maxX;
  657. y = num(x * area.height / area.width);
  658. } else { // 以y轴滑动距离为缩放基准
  659. maxY = validMax(maxY, max, isInclude, t, l, area.height / area.width);
  660. if(y > maxY) y = maxY;
  661. x = num(y * area.width / area.height);
  662. }
  663. areaOffset.left = x;
  664. areaOffset.top = y;
  665. }
  666. break;
  667. case 2: // 右上角
  668. x = num(x + areaOffset.right);
  669. y = num(y + areaOffset.top);
  670. if(x <= 0 && y >= 0) { // 有效滑动
  671. var w = (r === 1 ? img.height : img.width);
  672. var t = num(offset.y + m - area.top);
  673. var l = num(area.right + m - offset.x - w);
  674. var max = isIntersect && ((t >= 0) || (l >= 0))
  675. ? minimum(t, l)
  676. : false;
  677. if(-x > y && isReverse) { // 以x轴滑动距离为缩放基准
  678. maxX = validMax(maxX, max, isInclude, l, t, area.width / area.height);
  679. if(-x > maxX) x = -maxX;
  680. y = num(-x * area.height / area.width);
  681. } else { // 以y轴滑动距离为缩放基准
  682. maxY = validMax(maxY, max, isInclude, t, l, area.height / area.width);
  683. if(y > maxY) y = maxY;
  684. x = num(-y * area.width / area.height);
  685. }
  686. areaOffset.right = x;
  687. areaOffset.top = y;
  688. }
  689. break;
  690. case 3: // 左下角
  691. x += num(x + areaOffset.left);
  692. y += num(y + areaOffset.bottom);
  693. if(x >= 0 && y <= 0) { // 有效滑动
  694. var w = (r === 1 ? img.width : img.height);
  695. var t = num(area.bottom - m - offset.y - w);
  696. var l = num(offset.x - m - area.left);
  697. var max = isIntersect && ((l >= 0) || (t >= 0))
  698. ? minimum(t, l)
  699. : false;
  700. if(x > -y && isReverse) { // 以x轴滑动距离为缩放基准
  701. maxX = validMax(maxX, max, isInclude, l, t, area.width / area.height);
  702. if(x > maxX) x = maxX;
  703. y = num(-x * area.height / area.width);
  704. } else { // 以y轴滑动距离为缩放基准
  705. maxY = validMax(maxY, max, isInclude, t, l, area.height / area.width);
  706. if(-y > maxY) y = -maxY;
  707. x = num(-y * area.width / area.height);
  708. }
  709. areaOffset.left = x;
  710. areaOffset.bottom = y;
  711. }
  712. break;
  713. case 4: // 右下角
  714. x = num(x + areaOffset.right);
  715. y = num(y + areaOffset.bottom);
  716. if(x <= 0 && y <= 0) { // 有效滑动
  717. var w = (r === 1 ? img.height : img.width);
  718. var h = (r === 1 ? img.width : img.height);
  719. var t = num(area.bottom - offset.y - h - m);
  720. var l = num(area.right + m - offset.x - w);
  721. var max = isIntersect && ((l >= 0) || (t >= 0))
  722. ? minimum(t, l)
  723. : false;
  724. if(-x > -y && isReverse) { // 以x轴滑动距离为缩放基准
  725. maxX = validMax(maxX, max, isInclude, l, t, area.width / area.height);
  726. if(-x > maxX) x = -maxX;
  727. y = num(x * area.height / area.width);
  728. } else { // 以y轴滑动距离为缩放基准
  729. maxY = validMax(maxY, max, isInclude, t, l, area.height / area.width);
  730. if(-y > maxY) y = -maxY;
  731. x = num(y * area.width / area.height);
  732. }
  733. areaOffset.right = x;
  734. areaOffset.bottom = y;
  735. }
  736. break;
  737. }
  738. // console.log(x, y, JSON.stringify(areaOffset))
  739. changeAreaRect({
  740. instance: await this.getInstance(),
  741. });
  742. // this.draw();
  743. }
  744. } else if (e.touches.length == 2) { // 双点触摸缩放
  745. var start = getDistanceByTouches(touches);
  746. var end = getDistanceByTouches(e.touches);
  747. scaleImage({
  748. instance: await this.getInstance(),
  749. check: !area.bounce,
  750. scale: (end.c - start.c) / 100,
  751. x: end.x,
  752. y: end.y
  753. });
  754. touchType = 'scale';
  755. } else if(touchType === 'scale') {// 从双点触摸变成单点触摸 / 从缩放变成拖动
  756. touchType = 'move';
  757. } else {
  758. changeImageRect({
  759. instance: await this.getInstance(),
  760. check: !area.bounce,
  761. x: e.touches[0].pageX - touches[0].pageX,
  762. y: e.touches[0].pageY - touches[0].pageY
  763. });
  764. touchType = 'move';
  765. }
  766. touches = e.touches;
  767. },
  768. /**
  769. * 触摸结束
  770. * @param {Object} e 事件对象
  771. * @param {Object} o 组件实例对象
  772. */
  773. touchend: async function(e, o) {
  774. if(!img.src) return;
  775. if(touchType === 'stretch') { // 拉伸裁剪区域的四个角缩放
  776. // 裁剪区域宽度被缩放到多少
  777. var left = areaOffset.left;
  778. var right = areaOffset.right;
  779. var top = areaOffset.top;
  780. var bottom = areaOffset.bottom;
  781. var w = area.width + right - left;
  782. var h = area.height + bottom - top;
  783. // 图像放大倍数
  784. var p = scale * (area.width / w) - scale;
  785. // 复原裁剪区域
  786. areaOffset = { left: 0, right: 0, top: 0, bottom: 0 };
  787. changeAreaRect({
  788. instance: await this.getInstance(),
  789. });
  790. scaleImage({
  791. instance: await this.getInstance(),
  792. scale: p,
  793. x: area.left + left + (1 === activeAngle || 3 === activeAngle ? w : 0),
  794. y: area.top + top + (1 === activeAngle || 2 === activeAngle ? h : 0)
  795. });
  796. } else if (area.bounce) { // 检查边界并矫正,实现拖动到边界时有回弹效果
  797. changeImageRect({
  798. instance: await this.getInstance(),
  799. check: true
  800. });
  801. }
  802. },
  803. /**
  804. * 顺时针翻转图片90°
  805. * @param {Object} e 事件对象
  806. * @param {Object} o 组件实例对象
  807. */
  808. rotateImage: async function(r) {
  809. rotate = (rotate + (r || 90)) % 360;
  810. if(img.minScale >= 1 && area.checkRange) {
  811. // 因图片宽高可能不等,翻转后图片宽高需足够填满裁剪区域
  812. minScale = 1;
  813. if(img.width < area.height) {
  814. minScale = area.height / img.oldWidth;
  815. } else if(img.height < area.width) {
  816. minScale = area.width / img.oldHeight;
  817. }
  818. if(minScale !== 1) {
  819. scaleImage({
  820. instance: await this.getInstance(),
  821. scale: minScale - scale,
  822. x: sys.windowWidth / 2,
  823. y: (sys.windowHeight - sys.offsetBottom) / 2
  824. });
  825. }
  826. }
  827. // 由于拖动画布后会导致图片位置偏移,翻转时的旋转中心点需是图片区域+偏移区域的中心点
  828. // 翻转x轴中心点 = (超出裁剪区域右侧的图片宽度 - 超出裁剪区域左侧的图片宽度) / 2
  829. // 翻转y轴中心点 = (超出裁剪区域下方的图片宽度 - 超出裁剪区域上方的图片宽度) / 2
  830. var ox = ((offset.x + img.width - area.right) - (area.left - offset.x)) / 2;
  831. var oy = ((offset.y + img.height - area.bottom) - (area.top - offset.y)) / 2;
  832. changeImageRect({
  833. instance: await this.getInstance(),
  834. check: true,
  835. x: -ox - oy,
  836. y: -oy + ox
  837. });
  838. },
  839. rotateImage90: function() {
  840. this.rotateImage(90)
  841. },
  842. rotateImage270: function() {
  843. this.rotateImage(270)
  844. },
  845. }
  846. }