实现手机手势签字功能

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组件:

手机手势签字

效果图
相关推荐
偷光12 小时前
浏览器中的隐藏IDE: Elements (元素) 面板
开发语言·前端·ide·php
江拥羡橙16 小时前
Vue和React怎么选?全面比对
前端·vue.js·react.js
千码君201617 小时前
React Native:快速熟悉react 语法和企业级开发
javascript·react native·react.js·vite·hook
楼田莉子18 小时前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
暮之沧蓝18 小时前
Vue总结
前端·javascript·vue.js
木易 士心19 小时前
Promise深度解析:前端异步编程的核心
前端·javascript
im_AMBER19 小时前
Web 开发 21
前端·学习
又是忙碌的一天19 小时前
前端学习day01
前端·学习·html
Joker Zxc19 小时前
【前端基础】20、CSS属性——transform、translate、transition
前端·css
excel19 小时前
深入解析 Vue 3 源码:computed 的底层实现原理
前端·javascript·vue.js