使用Vue3实现手动签名的功能

要在Vue 3中实现手动签名的功能,可以结合Vue的模板和生命周期钩子函数来实现。下面是一个简单的示例代码:

<template>
  <div>
    <h1>手动签名</h1>
    <canvas ref="signatureCanvas" width="500" height="200" style="border:1px solid #000000;"></canvas>
    <br>
    <button @click="clearCanvas">清除</button>
    <button @click="saveSignature">保存</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isDrawing: false,
      lastX: 0,
      lastY: 0,
    };
  },
  mounted() {
    this.canvas = this.$refs.signatureCanvas;
    this.context = this.canvas.getContext("2d");

    this.canvas.addEventListener("mousedown", this.startDrawing);
    this.canvas.addEventListener("mousemove", this.draw);
    this.canvas.addEventListener("mouseup", this.stopDrawing);
    this.canvas.addEventListener("mouseleave", this.stopDrawing);
  },
  methods: {
    startDrawing(e) {
      this.isDrawing = true;
      this.lastX = e.offsetX;
      this.lastY = e.offsetY;
    },
    draw(e) {
      if (!this.isDrawing) return;

      this.context.beginPath();
      this.context.moveTo(this.lastX, this.lastY);
      this.context.lineTo(e.offsetX, e.offsetY);
      this.context.strokeStyle = "#000000";
      this.context.lineWidth = 2;
      this.context.stroke();
      
      this.lastX = e.offsetX;
      this.lastY = e.offsetY;
    },
    stopDrawing() {
      this.isDrawing = false;
    },
    clearCanvas() {
      this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    saveSignature() {
      const imageURL = this.canvas.toDataURL();
      // 在此处可以将imageURL发送到服务器保存,或进行其他处理
      console.log(imageURL);
    },
  },
};
</script>

这段代码是一个Vue组件,模板中包含了一个<canvas>元素用于绘制签名。通过ref属性,我们可以获取到对应的canvas元素,并在对应的生命周期钩子函数中注册事件监听器。绘制签名时,在mousedown、mousemove和mouseup事件中调用对应的方法来绘制路径、更新画笔坐标和状态。清除按钮调用clearCanvas方法来清除canvas内容,保存按钮调用saveSignature方法将canvas的内容转为base64编码的图像URL并打印到控制台。

你可以根据需要修改saveSignature方法,以便将签名图像发送到服务器保存或进行其他处理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容