MarkBody.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. <template>
  2. <div class="mark-body-container tw-flex-auto">
  3. <div v-if="!store.currentTask" class="tw-text-center">暂无评卷任务</div>
  4. <div v-else :style="{ width: answerPaperScale }">
  5. <div
  6. v-for="(item, index) in sliceImagesWithTrackList"
  7. :key="index"
  8. class="single-image-container"
  9. >
  10. <img
  11. :src="item.url"
  12. @click="(event) => makeScoreTrack(event, item)"
  13. draggable="false"
  14. />
  15. <MarkDrawTrack
  16. :track-list="item.trackList"
  17. :original-image="item.originalImage"
  18. :slice-image="item.sliceImage"
  19. :dx="item.dx"
  20. :dy="item.dy"
  21. />
  22. <hr class="image-seperator" />
  23. </div>
  24. </div>
  25. </div>
  26. <div class="cursor">
  27. <div class="cursor-border">
  28. <span class="text">{{ store.currentScore }}</span>
  29. </div>
  30. </div>
  31. </template>
  32. <script lang="ts">
  33. import {
  34. computed,
  35. defineComponent,
  36. onMounted,
  37. onUnmounted,
  38. reactive,
  39. watch,
  40. watchEffect,
  41. } from "vue";
  42. import { findCurrentTaskMarkResult, store } from "./store";
  43. import filters from "@/filters";
  44. import MarkDrawTrack from "./MarkDrawTrack.vue";
  45. import { ModeEnum, Track } from "@/types";
  46. import { useTimers } from "@/setups/useTimers";
  47. import { loadImage } from "@/utils/utils";
  48. import { groupBy, sortBy } from "lodash";
  49. // @ts-ignore
  50. import CustomCursor from "custom-cursor.js";
  51. interface SliceImage {
  52. url: string;
  53. indexInSliceUrls: number;
  54. trackList: Array<Track>;
  55. originalImage: HTMLImageElement;
  56. sliceImage: HTMLImageElement;
  57. dx: number;
  58. dy: number;
  59. accumTopHeight: number;
  60. effectiveWidth: number;
  61. }
  62. export default defineComponent({
  63. name: "MarkBody",
  64. components: { MarkDrawTrack },
  65. setup() {
  66. const { addTimeout } = useTimers();
  67. function hasSliceConfig() {
  68. return store.currentTask?.sliceConfig?.length;
  69. }
  70. let sliceImagesWithTrackList: Array<SliceImage> = reactive([]);
  71. let _studentId = -1; // 判断是否改变了任务
  72. let maxSliceWidth = 0; // 最大的裁切块宽度,图片容器以此为准
  73. let theFinalHeight = 0; // 最终宽度,用来定位轨迹在第几张图片,不包括image-seperator高度
  74. async function processSliceConfig() {
  75. // check if have MarkResult for currentTask
  76. let markResult = findCurrentTaskMarkResult();
  77. if (!markResult || !store.currentTask) return;
  78. // TODO: 图片加载出错,自动加载下一个任务
  79. for (const url of store.currentTask.sliceUrls) {
  80. await loadImage(filters.toCompleteUrl(url));
  81. }
  82. // 必须要先加载一遍,把“选择整图”的宽高重置后,再算总高度
  83. for (const sliceConfig of store.currentTask.sliceConfig) {
  84. const url = filters.toCompleteUrl(
  85. store.currentTask.sliceUrls[sliceConfig.i - 1]
  86. );
  87. const image = await loadImage(url);
  88. if (sliceConfig.w === 0 && sliceConfig.h === 0) {
  89. // 选择整图时,w/h 为0
  90. sliceConfig.w = image.naturalWidth;
  91. sliceConfig.h = image.naturalHeight;
  92. }
  93. }
  94. theFinalHeight = store.currentTask.sliceConfig
  95. .map((v) => v.h)
  96. .reduce((acc, v) => (acc += v));
  97. maxSliceWidth = Math.max(
  98. ...store.currentTask.sliceConfig.map((v) => v.w)
  99. );
  100. // 用来保存sliceImage在整个图片容器中(不包括image-seperator)的高度范围
  101. let accumTopHeight = 0;
  102. let accumBottomHeight = 0;
  103. for (const sliceConfig of store.currentTask.sliceConfig) {
  104. accumBottomHeight += sliceConfig.h;
  105. const url = filters.toCompleteUrl(
  106. store.currentTask.sliceUrls[sliceConfig.i - 1]
  107. );
  108. const image = await loadImage(url);
  109. const canvas = document.createElement("canvas");
  110. // canvas.width = sliceConfig.w;
  111. canvas.width = Math.max(sliceConfig.w, maxSliceWidth);
  112. canvas.height = sliceConfig.h;
  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. sliceConfig.x,
  121. sliceConfig.y,
  122. sliceConfig.w,
  123. sliceConfig.h,
  124. 0,
  125. 0,
  126. sliceConfig.w,
  127. sliceConfig.h
  128. );
  129. // console.log(image, canvas.height, sliceConfig, ctx);
  130. // console.log(canvas.toDataURL());
  131. const thisImageTrackList = markResult.trackList.filter(
  132. (v) => v.offsetIndex === sliceConfig.i
  133. );
  134. const dataUrl = canvas.toDataURL();
  135. const sliceImage = new Image();
  136. sliceImage.src = dataUrl;
  137. // sliceConfig.x + sliceConfig.w
  138. sliceImagesWithTrackList.push({
  139. url: dataUrl,
  140. indexInSliceUrls: sliceConfig.i,
  141. // 通过positionY来定位是第几张slice的还原,并过滤出相应的track
  142. trackList: thisImageTrackList.filter(
  143. (t) =>
  144. t.positionY >= accumTopHeight / theFinalHeight &&
  145. t.positionY < accumBottomHeight / theFinalHeight
  146. ),
  147. originalImage: image,
  148. sliceImage,
  149. dx: sliceConfig.x,
  150. dy: sliceConfig.y,
  151. accumTopHeight,
  152. effectiveWidth: sliceConfig.w,
  153. });
  154. accumTopHeight = accumBottomHeight;
  155. }
  156. }
  157. async function processSplitConfig() {
  158. // check if have MarkResult for currentTask
  159. let markResult = findCurrentTaskMarkResult();
  160. if (!markResult || !store.currentTask) return;
  161. const images = [];
  162. for (const url of store.currentTask.sliceUrls) {
  163. const image = await loadImage(filters.toCompleteUrl(url));
  164. images.push(image);
  165. }
  166. // TODO: add loading
  167. const splitConfigPairs = (store.setting.splitConfig
  168. .map((v, index, ary) => (index % 2 === 0 ? [v, ary[index + 1]] : false))
  169. .filter((v) => v) as unknown) as Array<[number, number]>;
  170. const maxSplitConfig = Math.max(...store.setting.splitConfig);
  171. maxSliceWidth =
  172. Math.max(...images.map((v) => v.naturalWidth)) * maxSplitConfig;
  173. theFinalHeight =
  174. splitConfigPairs.length *
  175. images.reduce((acc, v) => (acc += v.naturalHeight), 0);
  176. let accumTopHeight = 0;
  177. let accumBottomHeight = 0;
  178. for (const url of store.currentTask.sliceUrls) {
  179. const completeUrl = filters.toCompleteUrl(url);
  180. for (const config of splitConfigPairs) {
  181. const image = await loadImage(completeUrl);
  182. accumBottomHeight += image.naturalHeight;
  183. const width = image.naturalWidth * (config[1] - config[0]);
  184. const canvas = document.createElement("canvas");
  185. canvas.width = Math.max(width, maxSliceWidth);
  186. canvas.height = image.naturalHeight;
  187. const ctx = canvas.getContext("2d");
  188. if (!ctx) {
  189. console.log('canvas.getContext("2d") error');
  190. }
  191. // drawImage 画图软件透明色
  192. ctx?.drawImage(
  193. image,
  194. image.naturalWidth * config[0],
  195. 0,
  196. image.naturalWidth * config[1],
  197. image.naturalHeight,
  198. 0,
  199. 0,
  200. image.naturalWidth * config[1],
  201. image.naturalHeight
  202. );
  203. // console.log(image, canvas.height, sliceConfig, ctx);
  204. // console.log(canvas.toDataURL());
  205. const thisImageTrackList = markResult.trackList.filter(
  206. (t) =>
  207. t.offsetIndex ===
  208. (store.currentTask &&
  209. store.currentTask.sliceUrls.indexOf(url) + 1)
  210. );
  211. const dataUrl = canvas.toDataURL();
  212. const sliceImage = new Image();
  213. sliceImage.src = dataUrl;
  214. sliceImagesWithTrackList.push({
  215. url: canvas.toDataURL(),
  216. indexInSliceUrls: store.currentTask.sliceUrls.indexOf(url) + 1,
  217. trackList: thisImageTrackList.filter(
  218. (t) =>
  219. t.positionY >= accumTopHeight / theFinalHeight &&
  220. t.positionY < accumBottomHeight / theFinalHeight
  221. ),
  222. originalImage: image,
  223. sliceImage,
  224. dx: image.naturalWidth * config[0],
  225. dy: 0,
  226. accumTopHeight,
  227. effectiveWidth: image.naturalWidth * config[1],
  228. });
  229. accumTopHeight = accumBottomHeight;
  230. }
  231. }
  232. }
  233. // 供回退和清除使用
  234. // let trackLen = store.currentMarkResult?.trackList.length;
  235. const renderPaperAndMark = async () => {
  236. // check if have MarkResult for currentTask
  237. let markResult = findCurrentTaskMarkResult();
  238. if (!markResult || !store.currentTask) return;
  239. // console.log(markResult.trackList.length);
  240. // if (markResult.trackList.length !== trackLen) {
  241. // sliceImagesWithTrackList.splice(0);
  242. // trackLen = markResult.trackList.length;
  243. // }
  244. // reset sliceImagesWithTrackList ,当切换任务时,要重新绘制图片和轨迹
  245. if (_studentId !== store.currentTask.studentId) {
  246. // 还原轨迹用得上
  247. sliceImagesWithTrackList.splice(0);
  248. _studentId = store.currentTask.studentId;
  249. }
  250. if (hasSliceConfig()) {
  251. await processSliceConfig();
  252. } else {
  253. await processSplitConfig();
  254. }
  255. };
  256. watchEffect(renderPaperAndMark);
  257. const answerPaperScale = computed(() => {
  258. // 放大、缩小不影响页面之前的滚动条定位
  259. let percentWidth = 0;
  260. let percentTop = 0;
  261. const container = document.querySelector(
  262. ".mark-body-container"
  263. ) as HTMLDivElement;
  264. if (container) {
  265. const { scrollLeft, scrollTop, scrollWidth, scrollHeight } = container;
  266. percentWidth = scrollLeft / scrollWidth;
  267. percentTop = scrollTop / scrollHeight;
  268. }
  269. addTimeout(() => {
  270. if (container) {
  271. const { scrollWidth, scrollHeight } = container;
  272. container.scrollTo({
  273. left: scrollWidth * percentWidth,
  274. top: scrollHeight * percentTop,
  275. });
  276. }
  277. }, 10);
  278. const scale = store.setting.uiSetting["answer.paper.scale"];
  279. return scale * 100 + "%";
  280. });
  281. const makeScoreTrack = (event: MouseEvent, item: SliceImage) => {
  282. // console.log(item);
  283. if (!store.currentQuestion || typeof store.currentScore === "undefined")
  284. return;
  285. const target = event.target as HTMLImageElement;
  286. const track = {} as Track;
  287. track.mainNumber = store.currentQuestion?.mainNumber;
  288. track.subNumber = store.currentQuestion?.subNumber;
  289. track.number = (Date.now() - new Date(2010, 0, 0).valueOf()) / 10e7;
  290. track.score = store.currentScore;
  291. track.offsetIndex = item.indexInSliceUrls;
  292. track.offsetX = Math.round(
  293. event.offsetX * (target.naturalWidth / target.width) + item.dx
  294. );
  295. track.offsetY = Math.round(
  296. event.offsetY * (target.naturalHeight / target.height) + item.dy
  297. );
  298. track.positionX = (track.offsetX - item.dx) / maxSliceWidth;
  299. track.positionY =
  300. (track.offsetY - item.dy + item.accumTopHeight) / theFinalHeight;
  301. if (track.offsetX > item.effectiveWidth + item.dx) {
  302. console.log("不在有效宽度内,轨迹不生效");
  303. return;
  304. }
  305. store.currentScore = undefined;
  306. const markResult = findCurrentTaskMarkResult();
  307. if (markResult) {
  308. markResult.trackList = [...markResult.trackList, track];
  309. }
  310. item.trackList.push(track);
  311. };
  312. // 清除分数轨迹
  313. watchEffect(() => {
  314. for (const track of store.removeScoreTracks) {
  315. for (const sliceImage of sliceImagesWithTrackList) {
  316. sliceImage.trackList = sliceImage.trackList.filter(
  317. (t) =>
  318. !(
  319. t.mainNumber === track.mainNumber &&
  320. t.subNumber === track.subNumber &&
  321. t.number === track.number
  322. )
  323. );
  324. }
  325. }
  326. });
  327. // 轨迹模式下,添加轨迹,更新分数
  328. watch(
  329. () => store.currentMarkResult?.trackList,
  330. () => {
  331. const markResult = findCurrentTaskMarkResult();
  332. if (markResult && store.currentMarkResult) {
  333. const scoreGroups = groupBy(
  334. markResult.trackList,
  335. (obj) =>
  336. (obj.mainNumber + "").padStart(10, "0") +
  337. obj.subNumber.padStart(10, "0")
  338. );
  339. const questionWithScore = Object.entries(scoreGroups);
  340. const questionWithTotalScore = questionWithScore.map((v) => [
  341. v[0],
  342. v[1].reduce((acc, c) => (acc += c.score), 0),
  343. ]);
  344. const questionWithTotalScoreSorted = sortBy(
  345. questionWithTotalScore,
  346. (obj) => obj[0]
  347. );
  348. const scoreList = questionWithTotalScoreSorted.map((s) => s[1]);
  349. // console.log(
  350. // scoreGroups,
  351. // questionWithScore,
  352. // questionWithTotalScore,
  353. // questionWithTotalScoreSorted,
  354. // scoreList
  355. // );
  356. const cq = store.currentQuestion;
  357. if (cq) {
  358. cq.score =
  359. markResult.trackList
  360. .filter(
  361. (v) =>
  362. v.mainNumber === cq.mainNumber &&
  363. v.subNumber === cq.subNumber
  364. )
  365. .map((v) => v.score)
  366. .reduce((acc, v) => (acc += v * 100), 0) / 100;
  367. }
  368. markResult.scoreList = scoreList as number[];
  369. // const sortScore = orderBy(markResult.trackList, ['mainNumber', 'subNumber', 'score']);
  370. // markResult.scoreList = sortScore.reduce((acc, pre) => {
  371. // if(pre.mainNumber === cur.mainNumber && pre.subNumber === cur.subNumber) {
  372. // acc[acc.length-1] += cur.score
  373. // }
  374. // }, [0])
  375. markResult.markerScore =
  376. markResult.scoreList
  377. .filter((v): v is number => v !== null)
  378. .reduce((acc, v) => (acc += v * 100), 0) / 100;
  379. // console.log(markResult.scoreList, markResult.markerScore);
  380. // renderPaperAndMark();
  381. }
  382. },
  383. { deep: true }
  384. );
  385. watch(
  386. () => store.setting.mode,
  387. () => {
  388. const shouldHide = store.setting.mode === ModeEnum.COMMON;
  389. if (shouldHide) {
  390. // console.log("hide cursor", theCursor);
  391. theCursor && theCursor.destroy();
  392. } else {
  393. if (document.querySelector(".cursor")) {
  394. // console.log("show cursor", theCursor);
  395. // theCursor && theCursor.enable();
  396. theCursor = new CustomCursor(".cursor", {
  397. focusElements: [
  398. {
  399. selector: ".mark-body-container",
  400. focusClass: "cursor--focused-view",
  401. },
  402. ],
  403. }).initialize();
  404. }
  405. }
  406. }
  407. );
  408. let theCursor = null as any;
  409. onMounted(() => {
  410. if (store.setting.mode === ModeEnum.TRACK) {
  411. theCursor = new CustomCursor(".cursor", {
  412. focusElements: [
  413. {
  414. selector: ".mark-body-container",
  415. focusClass: "cursor--focused-view",
  416. },
  417. ],
  418. }).initialize();
  419. }
  420. });
  421. onUnmounted(() => {
  422. theCursor && theCursor.destroy();
  423. });
  424. return {
  425. store,
  426. sliceImagesWithTrackList,
  427. answerPaperScale,
  428. makeScoreTrack,
  429. };
  430. },
  431. // renderTriggered({ key, target, type }) {
  432. // console.log({ key, target, type });
  433. // },
  434. });
  435. </script>
  436. <style scoped>
  437. .mark-body-container {
  438. height: calc(100vh - 41px);
  439. overflow: scroll;
  440. background-size: 8px 8px;
  441. background-image: linear-gradient(to right, #e7e7e7 4px, transparent 4px),
  442. linear-gradient(to bottom, transparent 4px, #e7e7e7 4px);
  443. }
  444. .mark-body-container img {
  445. width: 100%;
  446. }
  447. .single-image-container {
  448. position: relative;
  449. }
  450. .image-seperator {
  451. border: 2px solid rgba(120, 120, 120, 0.1);
  452. }
  453. .hide-cursor {
  454. display: none !important;
  455. }
  456. .cursor {
  457. color: #ff5050;
  458. display: none;
  459. pointer-events: none;
  460. -webkit-user-select: none;
  461. -moz-user-select: none;
  462. -ms-user-select: none;
  463. user-select: none;
  464. top: 0;
  465. left: 0;
  466. position: fixed;
  467. will-change: transform;
  468. z-index: 1000;
  469. }
  470. .cursor-border {
  471. position: absolute;
  472. box-sizing: border-box;
  473. align-items: center;
  474. border: 1px solid #ff5050;
  475. border-radius: 50%;
  476. display: flex;
  477. justify-content: center;
  478. height: 0px;
  479. width: 0px;
  480. left: 0;
  481. top: 0;
  482. transform: translate(-50%, -50%);
  483. transition: all 360ms cubic-bezier(0.23, 1, 0.32, 1);
  484. }
  485. .cursor.cursor--initialized {
  486. display: block;
  487. }
  488. .cursor .text {
  489. font-size: 2rem;
  490. opacity: 0;
  491. transition: opacity 80ms cubic-bezier(0.23, 1, 0.32, 1);
  492. }
  493. .cursor.cursor--off-screen {
  494. opacity: 0;
  495. }
  496. .cursor.cursor--focused .cursor-border,
  497. .cursor.cursor--focused-view .cursor-border {
  498. width: 90px;
  499. height: 90px;
  500. }
  501. .cursor.cursor--focused-view .text {
  502. opacity: 1;
  503. transition: opacity 360ms cubic-bezier(0.23, 1, 0.32, 1);
  504. }
  505. </style>