实现手机手势签字功能

1、创建Canvas组件

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

javascript 复制代码
<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组件:

手机手势签字

效果图
相关推荐
小奶包他干奶奶15 分钟前
Webpack学习——Loader(文件转换器)
前端·学习·webpack
zy happy43 分钟前
若依 vue3 报错:找不到模块“@/api/xxxx/xxxxx”或其相应的类型声明。。Vue 3 can not find mod
前端·javascript·vue.js
潘小安1 小时前
Git Worktree + Claude Code:让你的开发效率翻倍的秘密武器
前端
meichaoWen1 小时前
【Vue3】vue3的全面学习(一)
前端·javascript·学习
小猪努力学前端2 小时前
在 React + React Router v7 SSR 项目里做多端适配,我踩的两个坑
前端·react.js
q***d1732 小时前
React桌面应用开发
前端·react.js·前端框架
8***29312 小时前
解决 Tomcat 跨域问题 - Tomcat 配置静态文件和 Java Web 服务(Spring MVC Springboot)同时允许跨域
java·前端·spring
0***142 小时前
React计算机视觉应用
前端·react.js·计算机视觉
Q***K552 小时前
React高级
前端·react.js·前端框架
c***97982 小时前
React语音识别案例
前端·react.js·语音识别