puzhibing
6 天以前 0db8c9b94a9ac655549d5eba5c2a6c92ac386c06
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
<template>
  <el-dialog title="确认签字" :visible.sync="visible" :width="dialogWidth" :close-on-click-modal="false"
    custom-class="signature-dialog" append-to-body @close="$emit('update:visible', false)">
    <div class="signature-container">
      <div class="signature-content">
        <canvas ref="signatureCanvas" :width="canvasWidth" :height="canvasHeight" @mousedown="startDrawing"
          @mousemove="draw" @mouseup="stopDrawing" @mouseleave="stopDrawing" @touchstart="handleTouchStart"
          @touchmove="handleTouchMove" @touchend="stopDrawing"></canvas>
      </div>
      <div class="signature-footer">
        <el-button type="default" @click="clearCanvas">重置</el-button>
        <el-button type="primary" @click="confirmSignature">确认</el-button>
      </div>
    </div>
  </el-dialog>
</template>
 
<script>
import { customUploadRequest, getUploadedFilePath } from '@/utils/utils'
import {editSignPicture} from './service'
export default {
  name: 'SignatureCanvas',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleType: JSON.parse(sessionStorage.getItem('userInfo')).roleType || 1,  // 1.超级管理员 2.审批人 3.工程师 4.实验员
      isDrawing: false,
      context: null,
      lastX: 0,
      lastY: 0,
      hasDrawn: false
    }
  },
  computed: {
    dialogWidth() {
      // 获取屏幕宽度的80%
      return window.innerWidth * 0.8 + 'px'
    },
    canvasWidth() {
      // 获取弹窗宽度的90%
      return window.innerWidth * 0.8 * 0.9
    },
    canvasHeight() {
      // 设置画布高度为宽度的1/3
      return this.canvasWidth / 3
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.$nextTick(() => {
          this.initCanvas()
          // 如果是实验员,加载保存的签名
          if (this.roleType == 4 || this.roleType == 3) {
            this.loadSavedSignature()
          }
          // 添加窗口大小改变的监听
          window.addEventListener('resize', this.handleResize)
        })
      } else {
        // 移除监听
        window.removeEventListener('resize', this.handleResize)
      }
    }
  },
  methods: {
    handleResize() {
      // 窗口大小改变时重新初始化画布
      this.$nextTick(() => {
        this.initCanvas()
        // 如果是实验员,重新加载保存的签名
        if ((this.roleType === 4 || this.roleType == 3) && this.savedSignature) {
          this.loadSavedSignature()
        }
      })
    },
    initCanvas() {
      const canvas = this.$refs.signatureCanvas
      this.context = canvas.getContext('2d')
      this.context.strokeStyle = 'rgba(4, 156, 154, 1)'
      this.context.lineWidth = 2
      this.context.lineCap = 'round'
      this.context.lineJoin = 'round'
 
      // 清空画布并绘制虚线边框
      this.clearCanvas()
    },
 
    drawDashedBorder() {
      const ctx = this.context
      ctx.setLineDash([5, 5])
      ctx.strokeStyle = '#dcdfe6'
      ctx.strokeRect(0, 0, this.canvasWidth, this.canvasHeight)
      ctx.setLineDash([])
      ctx.strokeStyle = 'rgba(4, 156, 154, 1)'
    },
 
    startDrawing(event) {
      this.isDrawing = true
      const rect = this.$refs.signatureCanvas.getBoundingClientRect()
      this.lastX = event.clientX - rect.left
      this.lastY = event.clientY - rect.top
    },
 
    draw(event) {
      if (!this.isDrawing) return
 
      const rect = this.$refs.signatureCanvas.getBoundingClientRect()
      const x = event.clientX - rect.left
      const y = event.clientY - rect.top
 
      this.context.beginPath()
      this.context.moveTo(this.lastX, this.lastY)
      this.context.lineTo(x, y)
      this.context.stroke()
 
      this.lastX = x
      this.lastY = y
      this.hasDrawn = true
    },
 
    handleTouchStart(event) {
      event.preventDefault()
      const touch = event.touches[0]
      const rect = this.$refs.signatureCanvas.getBoundingClientRect()
      this.lastX = touch.clientX - rect.left
      this.lastY = touch.clientY - rect.top
      this.isDrawing = true
    },
 
    handleTouchMove(event) {
      event.preventDefault()
      if (!this.isDrawing) return
 
      const touch = event.touches[0]
      const rect = this.$refs.signatureCanvas.getBoundingClientRect()
      const x = touch.clientX - rect.left
      const y = touch.clientY - rect.top
 
      this.context.beginPath()
      this.context.moveTo(this.lastX, this.lastY)
      this.context.lineTo(x, y)
      this.context.stroke()
 
      this.lastX = x
      this.lastY = y
      this.hasDrawn = true
    },
 
    stopDrawing() {
      this.isDrawing = false
    },
 
    clearCanvas() {
      this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
      this.drawDashedBorder()
      this.hasDrawn = false
    },
 
    confirmSignature() {
      const canvas = this.$refs.signatureCanvas
      const ctx = this.context
 
      // 校验是否签名
      if (this.isCanvasBlank()) {
        this.$message && this.$message.warning('请先确认签名')
        return
      }
 
      // 保存当前画布内容
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
 
      // 先填充背景色
      ctx.fillStyle = 'rgba(239, 248, 250, 1)'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
 
      // 创建一个临时画布来保存签名内容
      const tempCanvas = document.createElement('canvas')
      tempCanvas.width = canvas.width
      tempCanvas.height = canvas.height
      const tempCtx = tempCanvas.getContext('2d')
      tempCtx.putImageData(imageData, 0, 0)
 
      // 将签名内容绘制到主画布上
      ctx.drawImage(tempCanvas, 0, 0)
      // 导出图片为base64
      const base64Data = canvas.toDataURL('image/png');
 
      // 如果是实验员,保存签名到sessionStorage
      if (this.roleType == 4 || this.roleType == 3) {
        // 保存当前画布内容(包括背景色)
        // 保存到sessionStorage
        sessionStorage.setItem('experimenterSignature', base64Data)
      }
 
      // base64转blob
      const blob = this.dataURLtoBlob(base64Data);
      // 新增:生成带时间戳的文件名
      const timestamp = Date.now();
      const fileName = `signature_${timestamp}.png`;
      const file = new File([blob], fileName, { type: blob.type });
      // 上传
      customUploadRequest({
        file,
        onSuccess: (res) => {
          const url = getUploadedFilePath(res)
          if (!url) {
            this.$message.error('上传接口未返回文件地址')
            return
          }
          editSignPicture({ signPicture: url }).then(result => {
            if (result.code == 200) {
              this.$message.success('签名成功');
              this.$emit('confirm', url);
            }
          })
        },
        onError: (err) => {
          this.$message && this.$message.error ? this.$message.error('上传签名失败') : alert('上传签名失败');
        }
      });
    },
    // 加载保存的签名到画布(允许修改)
    loadSavedSignature() {
      const savedData = sessionStorage.getItem('experimenterSignature');
      console.log('savedData:,', savedData)
      if (savedData) {
        const canvas = this.$refs.signatureCanvas
        const ctx = this.context
        const img = new Image()
        img.onload = () => {
          // 清空画布
          ctx.clearRect(0, 0, canvas.width, canvas.height)
          // 绘制保存的签名
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
          // 重新绘制虚线边框
          this.drawDashedBorder()
          this.hasDrawn = true
          this.savedSignature = savedData
          // 不锁定画布,允许修改
        }
        img.src = savedData
      }
    },
    // 新增:base64转blob
    dataURLtoBlob(dataurl) {
      const arr = dataurl.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
 
    // 新增方法:判断画布是否为空白
    isCanvasBlank() {
      return !this.hasDrawn
    },
  },
  beforeDestroy() {
    // 组件销毁前移除监听
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>
 
<style lang="less" scoped>
.signature-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
 
  :deep(.el-dialog) {
    margin-top: 10vh !important;
  }
}
 
.signature-container {
  background: #fff;
  border-radius: 4px;
 
  .signature-content {
    padding: 20px;
    display: flex;
    justify-content: center;
 
    canvas {
      border-radius: 4px;
      background: rgba(239, 248, 250, 1);
      width: 100%;
      height: 100%;
    }
  }
 
  .signature-footer {
    padding: 20px;
    border-top: 1px solid #dcdfe6;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
 
    button {
      width: 150px;
    }
  }
}
</style>