实现手机手势签字功能

发布于:2025-03-16 ⋅ 阅读:(19) ⋅ 点赞:(0)
1、创建Canvas组件

在src/components目录下创建一个新的组件文件SignatureCanvas.vue:

<template>
  <div>
    <canvas
      ref="canvas"
      @mousedown="startDrawing"
      @mousemove="draw"
      @mouseup="stopDrawing"
      @mouseleave="stopDrawing"
      @touchstart="startDrawing"
      @touchmove="draw"
      @touchend="stopDrawing"
    ></canvas>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';

export default defineComponent({
  name: 'SignatureCanvas',
  setup() {
    const canvas = ref<HTMLCanvasElement | null>(null);
    let ctx: CanvasRenderingContext2D | null = null;
    let isDrawing = false;

    onMounted(() => {
      if (canvas.value) {
        ctx = canvas.value.getContext('2d');
        if (ctx) {
          ctx.lineWidth = 2;
          ctx.lineCap = 'round';
          ctx.strokeStyle = '#000';
        }
      }
    });

    const startDrawing = (event: MouseEvent | TouchEvent) => {
      isDrawing = true;
      const { offsetX, offsetY } = getEventPosition(event);
      if (ctx) {
        ctx.beginPath();
        ctx.moveTo(offsetX, offsetY);
      }
    };

    const draw = (event: MouseEvent | TouchEvent) => {
      if (!isDrawing) return;
      const { offsetX, offsetY } = getEventPosition(event);
      if (ctx) {
        ctx.lineTo(offsetX, offsetY);
        ctx.stroke();
      }
    };

    const stopDrawing = () => {
      isDrawing = false;
      if (ctx) {
        ctx.closePath();
      }
    };

    const getEventPosition = (event: MouseEvent | TouchEvent) => {
      if (canvas.value) {
        const rect = canvas.value.getBoundingClientRect();
        if (event instanceof TouchEvent) {
          const touch = event.touches[0];
          return {
            offsetX: touch.clientX - rect.left,
            offsetY: touch.clientY - rect.top,
          };
        } else {
          return {
            offsetX: event.offsetX,
            offsetY: event.offsetY,
          };
        }
      }
      return { offsetX: 0, offsetY: 0 };
    };

    return {
      canvas,
      startDrawing,
      draw,
      stopDrawing,
    };
  },
});
</script>

<style scoped>
canvas {
  border: 1px solid #000;
  touch-action: none; /* 防止触摸时页面滚动 */
}
</style>
2、在主组件中使用Canvas组件

在src/App.vue中使用刚刚创建的SignatureCanvas组件:

手机手势签字

效果图

在这里插入图片描述