前端|基于canvas封装一个签名的组件

346 阅读1分钟

前言

最近写了一个这样的需求,就是类似于审批的功能,其中需要用到首手写签名,因为用到审批的地方挺多的所以就封装成了组件,分享出来,方便下次直接套用😁😁

实现思路

使用Canvas元素作为签名区域,通过鼠标的点击、移动和释放事件来绘制签名。通过监听Canvas相关事件,我们可以获得鼠标在Canvas上的位置,并使用Canvas的绘图API(2D上下文)来绘制签名。

canvasWidthcanvasHeight用于设置Canvas的尺寸。
isDrawing表示是否正在绘制,
lastXlastY用于保存上一个绘制点的位置。

完整代码

<template>
  <div>
    <canvas ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
    <button @click="clearCanvas">清除</button>
    <button @click="saveImage">保存</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 400,
      canvasHeight: 200,
      isDrawing: false,
      lastX: 0,
      lastY: 0,
    };
  },
  mounted() {
    this.canvas = this.$refs.canvas;
    this.ctx = 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('mouseout', this.stopDrawing);
  },
  methods: {
    startDrawing(event) {
      this.isDrawing = true;
      const { offsetX, offsetY } = event;
      this.lastX = offsetX;
      this.lastY = offsetY;
    },
    draw(event) {
      if (!this.isDrawing) return;
      const { offsetX, offsetY } = event;
      this.ctx.beginPath();
      this.ctx.moveTo(this.lastX, this.lastY);
      this.ctx.lineTo(offsetX, offsetY);
      this.ctx.stroke();
      this.lastX = offsetX;
      this.lastY = offsetY;
    },
    stopDrawing() {
      this.isDrawing = false;
    },
    clearCanvas() { //清除
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    saveImage() {
      const dataURL = this.canvas.toDataURL();
      console.log(dataURL);
      // 在这里可以将dataURL发送到后端或进行进一步处理
    },
  },
};
</script>

效果

image.png