使用signature_pad实现数字签名

12/30/2022 技巧

# 使用 signature_pad 实现数字签名

# 安装

npm install --save signature_pad
1

# 创建组件

<template>
  <van-popup v-model="show" position="right" get-container="body" lazy-render :overlay="false" :style="{ height: '100%',width:'100%' }">
    <div class="wrap" id="signature-wrap">
      <div v-safeBottom class="button-view">
        <div v-for="(item,i) in btnList" class="btn item" @click="itemClick(i)" :class="{'close-btn':i===0}" :key="i">
          <img class="icon" :src="require(`../img/${item.icon}.png`)" alt="">
          <span class="text">{{item.text}}</span>
        </div>
        <div class="item submit-btn" @click="itemClick(3)">提 交</div>
      </div>
      <div class="canvas-wrap">
        <div class="border">
          <canvas ref="signaturePadCanvas" class="canvas"></canvas>
        </div>
        <p class="tip">请在框里写上您的签名</p>
      </div>
      <sh-loading :loading="loading"></sh-loading>
    </div>
  </van-popup>
</template>

<script>
import { mapState } from 'vuex'
import SignaturePad from "signature_pad";
import { SAVE_PERSON_SIGN, UPLOAD_SINGLE, GET_PERSON_SIGN } from '@/apis/listCommunication'
import { ImagePreview, Dialog } from 'vant';
export default {
  props: {
    fileName: String, //文件名
    signatureId: String, //签名人员 id
    options: { // 配置
      type: Object,
      default: () => {
        return {
          penColor: "#000000",   //笔刷颜色
          minWidth: 0.5,       //最小宽度
          maxWidth: 6,
          backgroundColor: '#f2f2f2'
        }
      }
    }
  },
  components: {
    [ImagePreview.Component.name]: ImagePreview.Component,
  },
  computed: {
    ...mapState(['user'])
  },
  data() {
    return {
      SignaturePad: null,
      fileList: [],
      show: false,
      loading: false,
      btnList: [
        { text: '退出', icon: 'close' },
        { text: '重写', icon: 'refresh' },
        { text: '预览', icon: 'preview' },
      ]
    }
  },
  mounted() {
    // 禁止页面复制
    document.onselectstart = new Function("event.returnValue=false");
  },
  methods: {
    open() {
      this.show = true
      this.$nextTick(() => {
        this.initSign()
      })
    },
    initSign() {
      const canvas = this.$refs.signaturePadCanvas;
      this.signaturePad = new SignaturePad(canvas, this.options);
      // window.addEventListener("resize", this.resizeCanvas);
      this.resizeCanvas();
      this.getSign()
    },
    // 重置写字板
    resizeCanvas() {
      const canvas = this.$refs.signaturePadCanvas;
      const ratio = Math.max(window.devicePixelRatio || 1, 1);
      canvas.width = canvas.offsetWidth * ratio;
      canvas.height = canvas.offsetHeight * ratio;
      canvas.getContext("2d").scale(ratio, ratio);
      this.signaturePad.clear();
    },
    itemClick(i) {
      switch (i) {
        case 0:
          let message = '确认关闭?'
          let confirmButtonText='退出'
          let cancelButtonText='取消'
          if (!this.signaturePad.isEmpty()) {
            message = '当前签名未提交,是否退出?'
          }
          Dialog.confirm({
            title: '提示',
            message,
            confirmButtonText,
            cancelButtonText,
            className: 'sign_close_dialog',
            getContainer: '#signature-wrap'
          })
            .then(() => {
              this.show = false
              this.$emit("cancel");
            })
            .catch(() => {
              // on cancel
            });
          break;
        case 1:
          this.signaturePad.clear();
          break;
        case 2:
          if (this.signaturePad.isEmpty()) {
            this.$toast({
              message: '暂无签名!',
              className: 'sign_empty_toast',
              getContainer: '#signature-wrap'
            })
            return;
          }
          const url = this.signaturePad.toDataURL();
          ImagePreview({
            images: [url],
            closeable: true,
          })
          break;
        case 3:
          if (this.signaturePad.isEmpty()) {
            this.$toast({
              message: '签名为空!',
              className: 'sign_empty_toast',
              getContainer: '#signature-wrap'
            })
            return;
          }
          const data = this.signaturePad.toDataURL();
          let fd = new FormData();
          let blob = this.dataURItoBlob(data, this.fileName);
          fd.append('files' + 1, blob);
          this.uploadFile(fd);
          break;
      }
    },
    // 获取用户签名
    getSign() {
      this.loading = true
      const id = this.signatureId || this.user.id
      this.$post(GET_PERSON_SIGN, { id }, data => {
        this.loading = false
        if (data.data.length && data.data[0].url) {
          this.signaturePad.fromDataURL(data.data[0].url);
        }
      },
        error => {
          this.$toast.fail(error.msg)
          this.loading = false
        }
      )
    },

    // 上传生成的签名图片
    uploadFile(fd) {
      const loading = this.$toast.loading("生成中...");
      this.$post(UPLOAD_SINGLE, fd, data => {
        this.fileList = data.data
        this.saveSign()
        loading.clear();
      }, error => {
        this.$toast.fail(error.msg)
        loading.clear();
      })
    },
    saveSign() {
      this.$post(SAVE_PERSON_SIGN, { fileList: this.fileList }, data => {
        this.$emit("confirm", this.fileList);
        this.$toast.success(data.msg)
        this.show = false
      })
    },
    // 将base64,转换成 file
    dataURItoBlob(dataUrl, filename = 'file') {
      const arr = dataUrl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
}
.border {
  border: 1px dashed #c0c7d4;
  box-sizing: border-box;
  height: 100%;
}
.canvas-wrap {
  height: 100%;
  width: 100%;
  width: calc(100% - 65px);
  padding: 20px 15px 20px 3px;
  position: relative;
  box-sizing: border-box;
  .tip {
    position: absolute;
    transform: rotate(90deg);
    top: 50%;
    left: -52px;
    color: #c0c7d4;
    font-size: 14px;
    z-index: 100;
  }
}
.canvas {
  height: 100%;
  width: 100%;
}
.button-view {
  height: 100%;
  width: 60px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-direction: column;
  background: #fff;
  padding-top: 35px;
  padding-bottom: 50px;
  position: relative;
  .item {
    transform: rotate(90deg);
  }
  .btn {
    display: flex;
    align-items: center;
    width: 100px;
    height: 40px;
    margin-bottom: 62px;
    .text {
      color: #515e78;
    }
    .icon {
      width: 24px;
      height: 24px;
      margin-right: 6px;
    }
  }
  .close-btn {
    position: absolute;
    top: 45px;
  }
  .submit-btn {
    width: 100px;
    height: 40px;
    border-radius: 4px;
    background-color: #3f7af3;
    color: #fff;
    text-align: center;
    line-height: 40px;
  }
}

#signature-wrap {
  ::v-deep.sign_close_dialog {
    transform: rotate(90deg);
    top: 37%;
    left: 10%;
  }
  ::v-deep.sign_empty_toast {
    transform: rotate(90deg);
    top: 48%;
    left: 37%;
  }
}
</style>
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

# 使用

this.$refs.sign.open()
1
Last Updated: 12/30/2022, 2:33:12 PM