user1
2024-06-21 7869653a258353bd70fc232630ab8467fa379bfe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
<template>
  <div class="matching">
    <div
      class="connect"
      id="connect"
      ref="connect"
      @mousemove="mousemove"
      @mouseup="(e) => touchend(e)"
    >
      <div class="answer">
        <div class="answer-box">
          <div
            class="answer-box-item"
            v-for="(item, index) in leftArr"
            :key="index"
            ref="left"
            @mousedown="(e) => touchstart(e, item, index)"
            :style="{ backgroundColor: primaryColor }"
            v-html="item.label.txt"
          ></div>
        </div>
        <div class="answer-box">
          <div
            class="answer-box-item tl-le"
            v-for="(item, index) in rightArr"
            :key="index"
            ref="right"
            :style="{ backgroundColor: primaryColor }"
            v-html="item.label.txt"
          ></div>
        </div>
      </div>
      <canvas
        class="connect-canvasA"
        :width="clientWidth"
        :height="clientHeight"
        ref="canvasA"
      ></canvas>
      <canvas
        class="connect-canvasB"
        :width="clientWidth"
        :height="clientHeight"
        ref="canvasB"
      ></canvas>
    </div>
    <!-- 按钮 -->
    <div class="btn-bottom">
      <el-button @click="submitData">提交</el-button>
      <el-button @click="saveData" :style="{ borderColor: primaryColor }"
        >保存</el-button
      >
      <el-button @click="redo">重做</el-button>
      <el-button @click="handleAnswer" :style="{ borderColor: primaryColor }"
        >查看答案</el-button
      >
    </div>
    <!-- 解析 -->
    <ul class="show-answer" v-if="isShowAnswer">
      <li v-if="isRight !== null">
        答案结果:<span v-if="isRight" style="color: #83e089">正确</span>
        <span v-if="isRight == false" style="color: #d81e06">错误</span>
      </li>
      <li class="show-answer-box">
        <div>答案:</div>
        <div>
          <img :src="question.answerImg" alt="" class="w100" />
        </div>
      </li>
    </ul>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      isDragging: false,
      leftArr: [],
      rightArr: [],
      location: [],
      canvasA: null,
      canvasB: null,
      leftDom: [],
      rightDom: [],
      clientWidth: 0,
      clientHeight: 0,
      scrollTop: 0,
      debounce: false,
      checkItem: null,
      checkItemIndex: null,
      isShowAnswer: false,
      isRight: null,
      value: [],
      pageNum: null,
    };
  },
  props: {
    rawData: {
      type: Object,
      default: () => {
        return {
          left: [],
          right: [],
        };
      },
    },
    question: {
      type: Object,
      default: () => {
        return [];
      },
    },
    primaryColor: {
      type: String,
      default: "#0bab87",
    },
  },
  watch: {
    rawData: {
      immediate: true,
      handler(val) {
        if (val.left && val.left.length) this.init();
      },
    },
  },
  mounted() {
    // 获取当前页码,用于匹配本次存储题目数据
    this.pageNum = this.handlePage();
    // 添加滚动事件 监听 解决因为滚动引起的拖动线不对的问题
    window.addEventListener(
      "scroll",
      (e) => {
        // 加个防抖
        if (this.debounce) clearTimeout(this.debounce);
        this.debounce = setTimeout(() => {
          this.debounce = false;
          this.scrollTop = e.target.scrollTop;
        }, 500);
      },
      true
    );
    let connect = this.$refs.connect;
    this.clientWidth = connect.clientWidth;
    this.clientHeight = connect.clientHeight;
    this.canvasA = this.$refs.canvasA.getContext("2d");
    this.canvasB = this.$refs.canvasB.getContext("2d");
    this.$nextTick(() => {
      this.drawing();
    });
    this.getAnswer();
  },
  methods: {
    init() {
      this.leftArr = this.rawData.left.map((r) => {
        return {
          label: r,
          line: [],
          value: [],
        };
      });
      this.rightArr = this.rawData.right.map((r) => {
        return {
          label: r,
        };
      });
      // 等dom 渲染完成
      this.$nextTick(() => {
        this.leftDom = this.$refs.left.map((r, i) => {
          return {
            bom: r,
            index: i,
          };
        });
        this.rightDom = this.$refs.right.map((r, i) => {
          return {
            bom: r,
            index: i,
          };
        });
        this.value.map((r) => {
          this.leftArr[r.left].line = this.attachment(r.left, r.right);
          this.leftArr[r.left].value = [r.right];
        });
        this.drawing();
      });
    },
    // 触摸结束
    touchend(e, index) {
      this.isDragging = false;
      if (this.question.showAnswer) {
        return false;
      }
      // let event = e.changedTouches[0];
      // document.elementFromPoint 重点,根据x,y坐标 取当前元素 所有能运行的逻辑 都依托于这里。
      let dom = (this.container ? this.container : document).elementFromPoint(
        e.pageX,
        e.pageY
      );
      // 右边的dom是哪个
      let right = this.rightDom.find((r) => r.bom === dom);
      // 不管是哪个都清除掉 底部的线
      this.canvasB.clearRect(0, 0, this.clientWidth, this.clientHeight);
      // 如果不是右边的dom 直接把 线 干掉 -- 证明不是 没有拖到右边上
      if (!right) {
        this.checkItem.line = [];
        return;
      }
      // 如果已有的不是我自己 直接替换掉上一个的
      if (this.checkItem.value[0] !== right.index) {
        let model = this.leftArr.find((r) => r.value[0] === right.index);
        if (model) {
          model.value = [];
          model.line = [];
        }
        this.checkItem.value = [right.index];
      }
      // 重新赋值 线的 x y 轴
      this.checkItem.line = this.attachment(this.checkItemIndex, right.index);
      this.drawing();
      let model = this.leftArr
        .map((r, i) => {
          return {
            left: i,
            right: r.value[0],
          };
        })
        .filter((r) => r.right !== undefined);
      this.$emit("input", model);
      this.question.userChoise = model;
      // console.log(JSON.stringify(model));
    },
    // 触摸开始
    touchstart(e, item, index) {
      this.isDragging = true;
      this.checkItem = item;
      this.checkItemIndex = index;
      e.stopPropagation();
      // let event = e.targetTouches[0];
      item.line = [
        e.pageX,
        e.pageY - this.$refs.connect.getBoundingClientRect().y + this.scrollTop,
      ];
    },
    // // 触摸中
    // touchmove(e, item) {
    //     if(!this.isDragging) return false
    //     console.log('移动',e);
    //     if (this.question.showAnswer) {
    //         return false;
    //     }
    //     // let event = e.targetTouches[0];
    //     item.line[2] = e.pageX;
    //     item.line[3] = e.pageY - this.$refs.connect.getBoundingClientRect().y + this.scrollTop;
    //     this.backstrockline(item.line);
    // },
 
    // 移动中
    mousemove(e) {
      if (!this.isDragging) return false;
      if (this.question.showAnswer) {
        return false;
      }
      this.checkItem.line[2] = e.pageX;
      this.checkItem.line[3] =
        e.pageY - this.$refs.connect.getBoundingClientRect().y + this.scrollTop;
      this.backstrockline(this.checkItem.line);
    },
 
    // 拖动的时候画线
    backstrockline(val) {
      let canvasB = this.canvasB;
      canvasB.clearRect(0, 0, this.clientWidth, this.clientHeight);
      canvasB.save();
      canvasB.beginPath();
      canvasB.lineWidth = 2;
      canvasB.moveTo(val[0], val[1]);
      canvasB.lineTo(val[2], val[3]);
      canvasB.strokeStyle = "#0C6";
      canvasB.stroke();
      canvasB.restore();
    },
    // 渲染出拖动之后的线
    drawing() {
      let canvasA = this.canvasA;
      this.canvasA.clearRect(0, 0, this.clientWidth, this.clientHeight);
      canvasA.beginPath();
      canvasA.lineWidth = 2;
      for (let i = 0; i < this.leftArr.length; i++) {
        const line = this.leftArr[i].line;
        // console.log(line);
        // console.log(this.leftArr[i]);
        if (line.length) {
          canvasA.moveTo(line[0], line[1]);
          canvasA.lineTo(line[2], line[3]);
        }
      }
      canvasA.strokeStyle = "#0C6";
      canvasA.stroke();
    },
    // 根据 左边 和右边的 index,换算出 左右的X,Y轴坐标
    attachment(index, rightIndex) {
      let leftEvent = this.leftDom[index].bom;
      let rightEvent = this.rightDom[rightIndex].bom;
      // 为了让线都在中间 x轴不用改 最简单
      let leftX = leftEvent.clientWidth + leftEvent.offsetLeft;
      let rightX = rightEvent.offsetLeft;
      let leftY = leftEvent.offsetTop + leftEvent.clientHeight / 2;
      let rightY = rightEvent.offsetTop + rightEvent.clientHeight / 2;
      return [leftX, leftY, rightX, rightY];
    },
    areArraysEqual(array1, array2) {
      // 如果两个数组长度不同,则它们不等
      if (array1.length !== array2.length) {
        return false;
      }
 
      // 遍历数组并比较每个对象的属性
      for (let i = 0; i < array1.length; i++) {
        const obj1 = array1[i];
        const obj2 = array2[i];
 
        // 如果对象的left或right属性不相等,则数组不等
        if (obj1.left !== obj2.left || obj1.right !== obj2.right) {
          return false;
        }
      }
 
      // 如果所有对象都匹配,则数组相等
      return true;
    },
    // 查看答案
    handleAnswer() {
      this.isShowAnswer = !this.isShowAnswer;
    },
    // 提交
    submitData() {
      const answerArr = [];
      const values = this.question.options.values;
      for (let index = 0; index < values.length; index++) {
        const item = values[index];
        const rightIndex = this.question.options.linkValues.findIndex(
          (citem) => citem.oldId == item.oldId
        );
 
        answerArr.push({
          left: index,
          right: rightIndex,
        });
      }
      console.log(this.question.userChoise,answerArr);
      this.isRight = this.areArraysEqual(this.question.userChoise, answerArr);
      this.isShowAnswer = true;
    },
    // 获取当前页码
    handlePage() {
      let pageNum = null;
      const element = (
        this.container ? this.container : document
      ).querySelector("matching");
      if (element) {
        pageNum = this.getParentWithClass(element, "page-box").getAttribute(
          "page"
        );
      }
      return pageNum;
    },
    getParentWithClass(element, className) {
      while (element.parentElement) {
        element = element.parentElement;
        if (element.classList.contains(className)) {
          return element;
        }
      }
    },
    // 获取本地存储题目答案
    getAnswer() {
      const data = localStorage.getItem(
        this.config.activeBook.name + "-matching-" + this.pageNum
      );
      if (data) {
        this.value = JSON.parse(data);
      }
    },
    // 保存
    saveData() {
      if (this.question.userChoise.length)
        localStorage.setItem(
          this.config.activeBook.name + "-matching-" + this.pageNum,
          JSON.stringify(this.question.userChoise)
        );
      // console.log('保存成功',this.config.activeBook.name,this.pageNum);
    },
    // 重做
    redo() {
      this.question.showAnswer = false;
      localStorage.removeItem(
        this.config.activeBook.name + "-matching-" + this.pageNum
      );
      this.value = [];
      for (let index = 0; index < this.leftArr.length; index++) {
        const item = this.leftArr[index];
        item.value = [];
        item.line = [];
      }
      this.leftArr;
      this.drawing();
      this.isShowAnswer = false;
    },
  },
};
</script>
 
<style lang="less" scoped>
.connect {
  position: relative;
  padding: 10px;
 
  &-canvasA {
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: 1;
  }
 
  &-canvasB {
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: 0;
  }
}
 
.answer {
  width: 100%;
  display: flex;
  justify-content: space-between;
 
  &-box {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 40%;
    text-align: center;
 
    &-item {
      cursor: pointer;
      z-index: 2;
      padding: 10px;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
      line-height: 24px;
      padding: 6px;
    }
 
    &-item:last-child {
      margin-bottom: 0;
    }
  }
}
.tl-le {
  text-align: left;
}
.connect {
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+/Edge */
  user-select: none; /* 标准语法 */
}
.show-answer {
  margin: 30px auto;
  width: 100%;
  height: min-content;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  li {
    padding: 10px;
  }
}
.btn-bottom {
  width: 70%;
  margin: 70px auto 0 auto;
  display: flex;
  justify-content: space-evenly;
  flex-wrap: wrap;
  .el-button {
    margin-top: 10px;
  }
}
.el-button {
  height: 30px;
  padding: 7px;
  min-width: 78px;
}
.answer-box-item {
  /deep/ .un1 {
    -webkit-text-emphasis-style: dot;
    -moz-text-emphasis-style: dot;
    -ms-text-emphasis-style: dot;
    text-emphasis-style: dot;
    -webkit-text-emphasis-position: under;
    -moz-text-emphasis-position: under;
    -ms-text-emphasis-position: under;
    text-emphasis-position: under;
  }
}
</style>