utils.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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(new Blob([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(new Blob([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(new Blob([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 || []).map((item) => {
  242. return { ...item };
  243. });
  244. const urls = [];
  245. for (let i = 0; i < sheetUrls.length; i++) {
  246. const url = sheetUrls[i];
  247. const configs = sheetConfig.filter((item) => item.i === i + 1);
  248. if (!configs.length) {
  249. urls[i] = url;
  250. continue;
  251. }
  252. const image = await loadImage(url);
  253. configs.forEach((item) => {
  254. item.x = image.naturalWidth * getNum(item.x);
  255. item.y = image.naturalHeight * getNum(item.y);
  256. item.w = image.naturalWidth * getNum(item.w);
  257. item.h = image.naturalHeight * getNum(item.h);
  258. });
  259. urls[i] = await getDataUrlForCoverConfig(image, configs);
  260. }
  261. return urls;
  262. }
  263. export async function preDrawImageHistory(_currentTask: Task | undefined) {
  264. console.log("preDrawImageHistory=>curTask:", _currentTask);
  265. if (!_currentTask?.taskId) return;
  266. let maxSliceWidth = 0; // 最大的裁切块宽度,图片容器以此为准
  267. // const hasSliceConfig = store.currentTask?.sliceConfig?.length;
  268. const hasSliceConfig = _currentTask?.sliceConfig?.length;
  269. // _currentTask.sheetUrls = ["/1-1.jpg", "/1-2.jpg"];
  270. _currentTask.sliceUrls = await processSliceUrls(_currentTask);
  271. const images = [];
  272. if (hasSliceConfig) {
  273. // 必须要先加载一遍,把“选择整图”的宽高重置后,再算总高度
  274. const sliceNum = _currentTask.sliceUrls.length;
  275. if (_currentTask.sliceConfig.some((v) => v.i > sliceNum)) {
  276. console.warn("裁切图设置的数量小于该学生的总图片数量");
  277. }
  278. _currentTask.sliceConfig = _currentTask.sliceConfig.filter(
  279. (v) => v.i <= sliceNum
  280. );
  281. for (const sliceConfig of _currentTask.sliceConfig) {
  282. const url = _currentTask.sliceUrls[sliceConfig.i - 1];
  283. const image = await loadImage(url);
  284. images[sliceConfig.i] = image;
  285. const { x, y, w, h } = sliceConfig;
  286. x < 0 && (sliceConfig.x = 0);
  287. y < 0 && (sliceConfig.y = 0);
  288. if (sliceConfig.w === 0 && sliceConfig.h === 0) {
  289. // 选择整图时,w/h 为0
  290. sliceConfig.w = image.naturalWidth;
  291. sliceConfig.h = image.naturalHeight;
  292. }
  293. if (x <= 1 && y <= 1 && sliceConfig.w <= 1 && sliceConfig.h <= 1) {
  294. sliceConfig.x = image.naturalWidth * x;
  295. sliceConfig.y = image.naturalHeight * y;
  296. sliceConfig.w = image.naturalWidth * w;
  297. sliceConfig.h = image.naturalHeight * h;
  298. }
  299. }
  300. maxSliceWidth = Math.max(..._currentTask.sliceConfig.map((v) => v.w));
  301. // 用来保存sliceImage在整个图片容器中(不包括image-seperator)的高度范围
  302. for (const sliceConfig of _currentTask.sliceConfig) {
  303. const url = _currentTask.sliceUrls[sliceConfig.i - 1];
  304. const image = images[sliceConfig.i];
  305. try {
  306. await getDataUrlForSliceConfig(image, sliceConfig, maxSliceWidth, url);
  307. } catch (error) {
  308. console.log("preDrawImage failed: ", error);
  309. }
  310. }
  311. } else {
  312. for (const url of _currentTask.sliceUrls) {
  313. const image = await loadImage(url);
  314. images.push(image);
  315. }
  316. const splitConfigPairs = store.setting.splitConfig.reduce<
  317. [number, number][]
  318. >((a, v, index) => {
  319. index % 2 === 0 ? a.push([v, -1]) : (a.at(-1)![1] = v);
  320. return a;
  321. }, []);
  322. const maxSplitConfig = Math.max(...store.setting.splitConfig);
  323. maxSliceWidth =
  324. Math.max(...images.map((v) => v.naturalWidth)) * maxSplitConfig;
  325. for (const url of _currentTask.sliceUrls) {
  326. for (const config of splitConfigPairs) {
  327. const indexInSliceUrls = _currentTask.sliceUrls.indexOf(url) + 1;
  328. const image = images[indexInSliceUrls - 1];
  329. try {
  330. await getDataUrlForSplitConfig(image, config, maxSliceWidth, url);
  331. } catch (error) {
  332. console.log("preDrawImage failed: ", error);
  333. }
  334. }
  335. }
  336. }
  337. }
  338. export function addFileServerPrefixToTask(rawTask: Task): Task {
  339. const newTask = JSON.parse(JSON.stringify(rawTask)) as Task;
  340. return newTask;
  341. }
  342. export function addHeaderTrackColorAttr(headerTrack: any): any {
  343. return headerTrack.map((item: any) => {
  344. item.color = "green";
  345. return item;
  346. });
  347. }
  348. /**
  349. * 获取随机code,默认获取16位
  350. * @param {Number} len 推荐8的倍数
  351. *
  352. */
  353. export function randomCode(len = 16): string {
  354. if (len <= 0) return;
  355. const steps = Math.ceil(len / 8);
  356. const stepNums = [];
  357. for (let i = 0; i < steps; i++) {
  358. const ranNum = Math.random().toString(32).slice(-8);
  359. stepNums.push(ranNum);
  360. }
  361. return stepNums.join("");
  362. }
  363. /**
  364. * 解析url获取指定参数值
  365. * @param urlStr url
  366. * @param paramName 参数名
  367. * @returns 参数值
  368. */
  369. export function parseHrefParam(
  370. urlStr: string,
  371. paramName: string = null
  372. ): string | object {
  373. if (!urlStr) return;
  374. const url = new URL(urlStr);
  375. const urlParams = new URLSearchParams(url.search);
  376. if (paramName) return urlParams.get(paramName);
  377. const params = {};
  378. for (const kv of urlParams.entries()) {
  379. params[kv[0]] = kv[1];
  380. }
  381. return params;
  382. }
  383. /**
  384. * 计算总数
  385. * @param {Array} dataList 需要统计的数组
  386. */
  387. export function calcSum(dataList: number[]): number {
  388. if (!dataList.length) return 0;
  389. return dataList.reduce(function (total, item) {
  390. return total + item;
  391. }, 0);
  392. }
  393. /** 获取数组最大数 */
  394. export function maxNum(dataList: number[]): number {
  395. if (!dataList.length) return 0;
  396. return Math.max.apply(null, dataList);
  397. }