utils.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import { store } from "@/store/store";
  2. import { PictureSlice, Task } from "@/types";
  3. // 打开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. return new Promise((resolve, reject) => {
  14. const image = new Image();
  15. image.setAttribute("crossorigin", "anonymous");
  16. image.src = url;
  17. image.onload = () => {
  18. resolve(image);
  19. };
  20. image.onerror = () => {
  21. reject("图片载入错误");
  22. };
  23. });
  24. }
  25. // 存放裁切图的ObjectUrls
  26. let objectUrlMap = new Map<string, string>();
  27. const OBJECT_URLS_MAP_MAX_SIZE =
  28. window.APP_OPTIONS?.OBJECT_URLS_MAP_MAX_SIZE ?? 100;
  29. export async function getDataUrlForSliceConfig(
  30. image: HTMLImageElement,
  31. sliceConfig: PictureSlice,
  32. maxSliceWidth: number,
  33. urlForCache: string
  34. ) {
  35. const { i, x, y, w, h } = sliceConfig;
  36. const key = `${urlForCache}-${i}-${x}-${y}-${w}-${h}`;
  37. if (objectUrlMap.get(key)) {
  38. console.log("cached slice objectUrl");
  39. return objectUrlMap.get(key);
  40. }
  41. const canvas = document.createElement("canvas");
  42. canvas.width = Math.max(sliceConfig.w, maxSliceWidth);
  43. canvas.height = sliceConfig.h;
  44. const ctx = canvas.getContext("2d");
  45. if (!ctx) {
  46. console.log('canvas.getContext("2d") error');
  47. throw new Error("canvas ctx error");
  48. }
  49. // drawImage 画图软件透明色
  50. ctx.drawImage(
  51. image,
  52. sliceConfig.x,
  53. sliceConfig.y,
  54. sliceConfig.w,
  55. sliceConfig.h,
  56. 0,
  57. 0,
  58. sliceConfig.w,
  59. sliceConfig.h
  60. );
  61. // console.log(image, canvas.height, sliceConfig, ctx);
  62. // console.log(canvas.toDataURL());
  63. // 如果用toBlob,则产生异步,而且URL.createObjectURL还会需要手动释放
  64. // const dataurl = canvas.toDataURL();
  65. const blob: Blob = await new Promise((res) => {
  66. canvas.toBlob((b) => res(b));
  67. });
  68. const dataurl = URL.createObjectURL(blob);
  69. cacheFIFO();
  70. objectUrlMap.set(key, dataurl);
  71. return dataurl;
  72. }
  73. // 清理缓存的过时数据(清除头10张),First in first out
  74. function cacheFIFO() {
  75. if (objectUrlMap.size > OBJECT_URLS_MAP_MAX_SIZE) {
  76. const ary = [...objectUrlMap.entries()];
  77. const toRelease = ary.splice(0, 10);
  78. // 为了避免部分图片还没显示就被revoke了,这里做一个延迟revoke
  79. // 此处有个瑕疵,缩略图的显示与试卷不是同时显示,是有可能被清除了的,只能让用户刷新了。 => 见下面的fix
  80. for (const u of toRelease) {
  81. // 如果当前图片仍在引用 objectUrl , 则将其放入缓存中
  82. if (document.querySelector(`img[src="${u[1]}"]`)) {
  83. ary.push(u);
  84. } else {
  85. // console.log("revoke ", u[1]);
  86. URL.revokeObjectURL(u[1]);
  87. }
  88. }
  89. objectUrlMap = new Map(ary);
  90. }
  91. }
  92. export async function getDataUrlForSplitConfig(
  93. image: HTMLImageElement,
  94. config: [number, number],
  95. maxSliceWidth: number,
  96. urlForCache: string
  97. ) {
  98. const [start, end] = config;
  99. const key = `${urlForCache}-${start}-${end}`;
  100. if (objectUrlMap.get(key)) {
  101. console.log("cached split objectUrl");
  102. return objectUrlMap.get(key);
  103. }
  104. const width = image.naturalWidth * (end - start);
  105. const canvas = document.createElement("canvas");
  106. canvas.width = Math.max(width, maxSliceWidth);
  107. canvas.height = image.naturalHeight;
  108. const ctx = canvas.getContext("2d");
  109. if (!ctx) {
  110. console.log('canvas.getContext("2d") error');
  111. throw new Error("canvas ctx error");
  112. }
  113. // drawImage 画图软件透明色
  114. ctx.drawImage(
  115. image,
  116. image.naturalWidth * start,
  117. 0,
  118. image.naturalWidth * end,
  119. image.naturalHeight,
  120. 0,
  121. 0,
  122. image.naturalWidth * end,
  123. image.naturalHeight
  124. );
  125. // 如果用toBlob,则产生异步,而且URL.createObjectURL还会需要手动释放
  126. // const dataurl = canvas.toDataURL();
  127. const blob: Blob = await new Promise((res) => {
  128. canvas.toBlob((b) => res(b));
  129. });
  130. const dataurl = URL.createObjectURL(blob);
  131. cacheFIFO();
  132. objectUrlMap.set(key, dataurl);
  133. return dataurl;
  134. }
  135. export async function getDataUrlForCoverConfig(
  136. image: HTMLImageElement,
  137. configs: PictureSlice[]
  138. ) {
  139. const key = `${image.src}`;
  140. if (objectUrlMap.get(key)) {
  141. return objectUrlMap.get(key);
  142. }
  143. const canvas = document.createElement("canvas");
  144. canvas.width = image.naturalWidth;
  145. canvas.height = image.naturalHeight;
  146. const ctx = canvas.getContext("2d");
  147. if (!ctx) {
  148. console.log('canvas.getContext("2d") error');
  149. throw new Error("canvas ctx error");
  150. }
  151. ctx.drawImage(image, 0, 0);
  152. ctx.fillStyle = "#ffffff";
  153. configs.forEach((config) => {
  154. ctx.fillRect(config.x, config.y, config.w, config.h);
  155. });
  156. const blob: Blob = await new Promise((res) => {
  157. canvas.toBlob((b) => res(b));
  158. });
  159. const dataurl = URL.createObjectURL(blob);
  160. cacheFIFO();
  161. objectUrlMap.set(key, dataurl);
  162. return dataurl;
  163. }
  164. export async function preDrawImage(_currentTask: Task | undefined) {
  165. // console.log("preDrawImage=>curTask:", _currentTask);
  166. if (!_currentTask?.taskId) return;
  167. let maxSliceWidth = 0; // 最大的裁切块宽度,图片容器以此为准
  168. // const hasSliceConfig = store.currentTask?.sliceConfig?.length;
  169. const hasSliceConfig = _currentTask?.sliceConfig?.length;
  170. const images = [];
  171. if (hasSliceConfig) {
  172. // 必须要先加载一遍,把“选择整图”的宽高重置后,再算总高度
  173. const sliceNum = _currentTask.sliceUrls.length;
  174. if (_currentTask.sliceConfig.some((v) => v.i > sliceNum)) {
  175. console.warn("裁切图设置的数量小于该学生的总图片数量");
  176. }
  177. _currentTask.sliceConfig = _currentTask.sliceConfig.filter(
  178. (v) => v.i <= sliceNum
  179. );
  180. for (const sliceConfig of _currentTask.sliceConfig) {
  181. const url = _currentTask.sliceUrls[sliceConfig.i - 1];
  182. const image = await loadImage(url);
  183. images[sliceConfig.i] = image;
  184. const { x, y, w, h } = sliceConfig;
  185. x < 0 && (sliceConfig.x = 0);
  186. y < 0 && (sliceConfig.y = 0);
  187. if (sliceConfig.w === 0 && sliceConfig.h === 0) {
  188. // 选择整图时,w/h 为0
  189. sliceConfig.w = image.naturalWidth;
  190. sliceConfig.h = image.naturalHeight;
  191. }
  192. if (x <= 1 && y <= 1 && sliceConfig.w <= 1 && sliceConfig.h <= 1) {
  193. sliceConfig.x = image.naturalWidth * x;
  194. sliceConfig.y = image.naturalHeight * y;
  195. sliceConfig.w = image.naturalWidth * w;
  196. sliceConfig.h = image.naturalHeight * h;
  197. }
  198. }
  199. maxSliceWidth = Math.max(..._currentTask.sliceConfig.map((v) => v.w));
  200. // 用来保存sliceImage在整个图片容器中(不包括image-seperator)的高度范围
  201. for (const sliceConfig of _currentTask.sliceConfig) {
  202. const url = _currentTask.sliceUrls[sliceConfig.i - 1];
  203. const image = images[sliceConfig.i];
  204. try {
  205. await getDataUrlForSliceConfig(image, sliceConfig, maxSliceWidth, url);
  206. } catch (error) {
  207. console.log("preDrawImage failed: ", error);
  208. }
  209. }
  210. } else {
  211. for (const url of _currentTask.sliceUrls) {
  212. const image = await loadImage(url);
  213. images.push(image);
  214. }
  215. const splitConfigPairs = store.setting.splitConfig.reduce<
  216. [number, number][]
  217. >((a, v, index) => {
  218. index % 2 === 0 ? a.push([v, -1]) : (a.at(-1)![1] = v);
  219. return a;
  220. }, []);
  221. const maxSplitConfig = Math.max(...store.setting.splitConfig);
  222. maxSliceWidth =
  223. Math.max(...images.map((v) => v.naturalWidth)) * maxSplitConfig;
  224. for (const url of _currentTask.sliceUrls) {
  225. for (const config of splitConfigPairs) {
  226. const indexInSliceUrls = _currentTask.sliceUrls.indexOf(url) + 1;
  227. const image = images[indexInSliceUrls - 1];
  228. try {
  229. await getDataUrlForSplitConfig(image, config, maxSliceWidth, url);
  230. } catch (error) {
  231. console.log("preDrawImage failed: ", error);
  232. }
  233. }
  234. }
  235. }
  236. }
  237. export async function processSliceUrls(_currentTask: Task | undefined) {
  238. if (!_currentTask?.taskId) return;
  239. const getNum = (num) => Math.max(Math.min(1, num), 0);
  240. const sheetUrls = _currentTask.sheetUrls || [];
  241. const sheetConfig = store.setting.sheetConfig || [];
  242. const urls = [];
  243. for (let i = 0; i < sheetUrls.length; i++) {
  244. const url = sheetUrls[i];
  245. const configs = sheetConfig.filter((item) => item.i === i + 1);
  246. if (!configs.length) {
  247. urls[i] = url;
  248. continue;
  249. }
  250. const image = await loadImage(url);
  251. configs.forEach((item) => {
  252. item.x = image.naturalWidth * getNum(item.x);
  253. item.y = image.naturalHeight * getNum(item.y);
  254. item.w = image.naturalWidth * getNum(item.w);
  255. item.h = image.naturalHeight * getNum(item.h);
  256. });
  257. urls[i] = await getDataUrlForCoverConfig(image, configs);
  258. }
  259. return urls;
  260. }
  261. export async function preDrawImageHistory(_currentTask: Task | undefined) {
  262. console.log("preDrawImageHistory=>curTask:", _currentTask);
  263. if (!_currentTask?.taskId) return;
  264. let maxSliceWidth = 0; // 最大的裁切块宽度,图片容器以此为准
  265. // const hasSliceConfig = store.currentTask?.sliceConfig?.length;
  266. const hasSliceConfig = _currentTask?.sliceConfig?.length;
  267. _currentTask.sheetUrls = ["/1-1.jpg", "/1-2.jpg"];
  268. _currentTask.sliceUrls = await processSliceUrls(_currentTask);
  269. const images = [];
  270. if (hasSliceConfig) {
  271. // 必须要先加载一遍,把“选择整图”的宽高重置后,再算总高度
  272. const sliceNum = _currentTask.sliceUrls.length;
  273. if (_currentTask.sliceConfig.some((v) => v.i > sliceNum)) {
  274. console.warn("裁切图设置的数量小于该学生的总图片数量");
  275. }
  276. _currentTask.sliceConfig = _currentTask.sliceConfig.filter(
  277. (v) => v.i <= sliceNum
  278. );
  279. for (const sliceConfig of _currentTask.sliceConfig) {
  280. const url = _currentTask.sliceUrls[sliceConfig.i - 1];
  281. const image = await loadImage(url);
  282. images[sliceConfig.i] = image;
  283. const { x, y, w, h } = sliceConfig;
  284. x < 0 && (sliceConfig.x = 0);
  285. y < 0 && (sliceConfig.y = 0);
  286. if (sliceConfig.w === 0 && sliceConfig.h === 0) {
  287. // 选择整图时,w/h 为0
  288. sliceConfig.w = image.naturalWidth;
  289. sliceConfig.h = image.naturalHeight;
  290. }
  291. if (x <= 1 && y <= 1 && sliceConfig.w <= 1 && sliceConfig.h <= 1) {
  292. sliceConfig.x = image.naturalWidth * x;
  293. sliceConfig.y = image.naturalHeight * y;
  294. sliceConfig.w = image.naturalWidth * w;
  295. sliceConfig.h = image.naturalHeight * h;
  296. }
  297. }
  298. maxSliceWidth = Math.max(..._currentTask.sliceConfig.map((v) => v.w));
  299. // 用来保存sliceImage在整个图片容器中(不包括image-seperator)的高度范围
  300. for (const sliceConfig of _currentTask.sliceConfig) {
  301. const url = _currentTask.sliceUrls[sliceConfig.i - 1];
  302. const image = images[sliceConfig.i];
  303. try {
  304. await getDataUrlForSliceConfig(image, sliceConfig, maxSliceWidth, url);
  305. } catch (error) {
  306. console.log("preDrawImage failed: ", error);
  307. }
  308. }
  309. } else {
  310. for (const url of _currentTask.sliceUrls) {
  311. const image = await loadImage(url);
  312. images.push(image);
  313. }
  314. const splitConfigPairs = store.setting.splitConfig.reduce<
  315. [number, number][]
  316. >((a, v, index) => {
  317. index % 2 === 0 ? a.push([v, -1]) : (a.at(-1)![1] = v);
  318. return a;
  319. }, []);
  320. const maxSplitConfig = Math.max(...store.setting.splitConfig);
  321. maxSliceWidth =
  322. Math.max(...images.map((v) => v.naturalWidth)) * maxSplitConfig;
  323. for (const url of _currentTask.sliceUrls) {
  324. for (const config of splitConfigPairs) {
  325. const indexInSliceUrls = _currentTask.sliceUrls.indexOf(url) + 1;
  326. const image = images[indexInSliceUrls - 1];
  327. try {
  328. await getDataUrlForSplitConfig(image, config, maxSliceWidth, url);
  329. } catch (error) {
  330. console.log("preDrawImage failed: ", error);
  331. }
  332. }
  333. }
  334. }
  335. }
  336. export function addFileServerPrefixToTask(rawTask: Task): Task {
  337. const newTask = JSON.parse(JSON.stringify(rawTask)) as Task;
  338. return newTask;
  339. }
  340. export function addHeaderTrackColorAttr(headerTrack: any): any {
  341. return headerTrack.map((item: any) => {
  342. item.color = "green";
  343. return item;
  344. });
  345. }
  346. /**
  347. * 获取随机code,默认获取16位
  348. * @param {Number} len 推荐8的倍数
  349. *
  350. */
  351. export function randomCode(len = 16): string {
  352. if (len <= 0) return;
  353. const steps = Math.ceil(len / 8);
  354. const stepNums = [];
  355. for (let i = 0; i < steps; i++) {
  356. const ranNum = Math.random().toString(32).slice(-8);
  357. stepNums.push(ranNum);
  358. }
  359. return stepNums.join("");
  360. }
  361. /**
  362. * 解析url获取指定参数值
  363. * @param urlStr url
  364. * @param paramName 参数名
  365. * @returns 参数值
  366. */
  367. export function parseHrefParam(
  368. urlStr: string,
  369. paramName: string = null
  370. ): string | object {
  371. if (!urlStr) return;
  372. const url = new URL(urlStr);
  373. const urlParams = new URLSearchParams(url.search);
  374. if (paramName) return urlParams.get(paramName);
  375. const params = {};
  376. for (const kv of urlParams.entries()) {
  377. params[kv[0]] = kv[1];
  378. }
  379. return params;
  380. }
  381. /**
  382. * 计算总数
  383. * @param {Array} dataList 需要统计的数组
  384. */
  385. export function calcSum(dataList) {
  386. if (!dataList.length) return 0;
  387. return dataList.reduce(function (total, item) {
  388. return total + item;
  389. }, 0);
  390. }