utils.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import { store } from "@/features/mark/store";
  2. import { PictureSlice, Task } from "@/types";
  3. // TODO: 打开cache后,会造成没有 vue devtools 时,canvas缓存错误,暂时不知道原因
  4. // 通过回看的测试,打开回看,再关闭回看,稍等一会儿再打开回看,确实可以看到该缓存时缓存了,该丢弃时丢弃了
  5. // 把store.currentTask当做 weakRef ,当它不存在时,就丢弃它所有的图片
  6. const weakedMapImages = new WeakMap<Object, Map<string, HTMLImageElement>>();
  7. /**
  8. * 异步获取图片
  9. * @param url 完整的图片路径
  10. * @returns Promise<HTMLImageElement>
  11. */
  12. export async function loadImage(url: string): Promise<HTMLImageElement> {
  13. // if (store.currentTask && weakedMapImages.get(store.currentTask)) {
  14. // const imagesCache = weakedMapImages.get(store.currentTask);
  15. // if (imagesCache) {
  16. // // console.log("cached image", url);
  17. // const image = imagesCache.get(url);
  18. // if (image) return image;
  19. // }
  20. // }
  21. // else loading image
  22. return new Promise((resolve, reject) => {
  23. const image = new Image();
  24. image.setAttribute("crossorigin", "anonymous");
  25. image.src = url;
  26. image.onload = () => {
  27. // if (store.currentTask) {
  28. // let imagesCache = weakedMapImages.get(store.currentTask);
  29. // if (!imagesCache) {
  30. // imagesCache = new Map<string, HTMLImageElement>();
  31. // weakedMapImages.set(store.currentTask, imagesCache);
  32. // }
  33. // imagesCache.set(url, image);
  34. // }
  35. resolve(image);
  36. };
  37. image.onerror = reject;
  38. });
  39. }
  40. // 存放裁切图的ObjectUrls
  41. let objectUrlMap = new Map<string, string>();
  42. const OBJECT_URLS_MAP_MAX_SIZE = 100;
  43. export async function getDataUrlForSliceConfig(
  44. image: HTMLImageElement,
  45. sliceConfig: PictureSlice,
  46. maxSliceWidth: number,
  47. urlForCache: string
  48. ) {
  49. const { i, x, y, w, h } = sliceConfig;
  50. const key = `${urlForCache}-${i}-${x}-${y}-${w}-${h}`;
  51. if (objectUrlMap.get(key)) {
  52. console.log("cached slice objectUrl");
  53. return objectUrlMap.get(key);
  54. }
  55. const canvas = document.createElement("canvas");
  56. canvas.width = Math.max(sliceConfig.w, maxSliceWidth);
  57. canvas.height = sliceConfig.h;
  58. const ctx = canvas.getContext("2d");
  59. if (!ctx) {
  60. console.log('canvas.getContext("2d") error');
  61. }
  62. // drawImage 画图软件透明色
  63. ctx?.drawImage(
  64. image,
  65. sliceConfig.x,
  66. sliceConfig.y,
  67. sliceConfig.w,
  68. sliceConfig.h,
  69. 0,
  70. 0,
  71. sliceConfig.w,
  72. sliceConfig.h
  73. );
  74. // console.log(image, canvas.height, sliceConfig, ctx);
  75. // console.log(canvas.toDataURL());
  76. // 如果用toBlob,则产生异步,而且URL.createObjectURL还会需要手动释放
  77. // const dataurl = canvas.toDataURL();
  78. const blob = await new Promise((res) => {
  79. canvas.toBlob(res);
  80. });
  81. const dataurl = URL.createObjectURL(blob);
  82. cacheFIFO();
  83. objectUrlMap.set(key, dataurl);
  84. return dataurl;
  85. }
  86. // 清理缓存的过时数据(清除头10张),First in first out
  87. function cacheFIFO() {
  88. if (objectUrlMap.size > OBJECT_URLS_MAP_MAX_SIZE) {
  89. const ary = [...objectUrlMap.entries()];
  90. const toRelease = ary.splice(0, 10);
  91. for (const u of toRelease) {
  92. URL.revokeObjectURL(u[1]);
  93. }
  94. objectUrlMap = new Map(ary);
  95. }
  96. }
  97. export async function getDataUrlForSplitConfig(
  98. image: HTMLImageElement,
  99. config: [number, number],
  100. maxSliceWidth: number,
  101. urlForCache: string
  102. ) {
  103. const [start, end] = config;
  104. const key = `${urlForCache}-${start}-${end}`;
  105. if (objectUrlMap.get(key)) {
  106. console.log("cached split objectUrl");
  107. return objectUrlMap.get(key);
  108. }
  109. const width = image.naturalWidth * (end - start);
  110. const canvas = document.createElement("canvas");
  111. canvas.width = Math.max(width, maxSliceWidth);
  112. canvas.height = image.naturalHeight;
  113. const ctx = canvas.getContext("2d");
  114. if (!ctx) {
  115. console.log('canvas.getContext("2d") error');
  116. }
  117. // drawImage 画图软件透明色
  118. ctx?.drawImage(
  119. image,
  120. image.naturalWidth * start,
  121. 0,
  122. image.naturalWidth * end,
  123. image.naturalHeight,
  124. 0,
  125. 0,
  126. image.naturalWidth * end,
  127. image.naturalHeight
  128. );
  129. // 如果用toBlob,则产生异步,而且URL.createObjectURL还会需要手动释放
  130. // const dataurl = canvas.toDataURL();
  131. const blob = await new Promise((res) => {
  132. canvas.toBlob(res);
  133. });
  134. const dataurl = URL.createObjectURL(blob);
  135. cacheFIFO();
  136. objectUrlMap.set(key, dataurl);
  137. return dataurl;
  138. }
  139. export async function preDrawImage(_currentTask: Task) {
  140. if (!_currentTask?.libraryId) return;
  141. let maxSliceWidth = 0; // 最大的裁切块宽度,图片容器以此为准
  142. const hasSliceConfig = store.currentTask?.sliceConfig?.length;
  143. const images = [];
  144. if (hasSliceConfig) {
  145. // 必须要先加载一遍,把“选择整图”的宽高重置后,再算总高度
  146. for (const sliceConfig of _currentTask.sliceConfig) {
  147. const url = _currentTask.sliceUrls[sliceConfig.i - 1];
  148. const image = await loadImage(url);
  149. images[sliceConfig.i] = image;
  150. if (sliceConfig.w === 0 && sliceConfig.h === 0) {
  151. // 选择整图时,w/h 为0
  152. sliceConfig.w = image.naturalWidth;
  153. sliceConfig.h = image.naturalHeight;
  154. }
  155. }
  156. maxSliceWidth = Math.max(..._currentTask.sliceConfig.map((v) => v.w));
  157. // 用来保存sliceImage在整个图片容器中(不包括image-seperator)的高度范围
  158. for (const sliceConfig of _currentTask.sliceConfig) {
  159. const url = _currentTask.sliceUrls[sliceConfig.i - 1];
  160. const image = images[sliceConfig.i];
  161. (await getDataUrlForSliceConfig(
  162. image,
  163. sliceConfig,
  164. maxSliceWidth,
  165. url
  166. )) as string;
  167. }
  168. } else {
  169. for (const url of _currentTask.sliceUrls) {
  170. const image = await loadImage(url);
  171. images.push(image);
  172. }
  173. const splitConfigPairs = store.setting.splitConfig
  174. .map((v, index, ary) => (index % 2 === 0 ? [v, ary[index + 1]] : false))
  175. .filter((v) => v) as unknown as Array<[number, number]>;
  176. const maxSplitConfig = Math.max(...store.setting.splitConfig);
  177. maxSliceWidth =
  178. Math.max(...images.map((v) => v.naturalWidth)) * maxSplitConfig;
  179. for (const url of _currentTask.sliceUrls) {
  180. for (const config of splitConfigPairs) {
  181. const indexInSliceUrls = _currentTask.sliceUrls.indexOf(url) + 1;
  182. const image = images[indexInSliceUrls - 1];
  183. (await getDataUrlForSplitConfig(
  184. image,
  185. config,
  186. maxSliceWidth,
  187. url
  188. )) as string;
  189. }
  190. }
  191. }
  192. }