实现手机手势签字功能

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

手机手势签字

效果图
相关推荐
敲厉害的燕宝3 分钟前
Pinia——Vue的Store状态管理库
前端·javascript·vue.js
Aphasia31125 分钟前
react必备JavaScript知识点(二)——类
前端·javascript
玖玖passion27 分钟前
数组转树:数据结构中的经典问题
前端
呼Lu噜34 分钟前
WPF-遵循MVVM框架创建图表的显示【保姆级】
前端·后端·wpf
珠峰下的沙砾37 分钟前
Vue3 里 CSS 深度作用选择器 :global
前端·javascript·css
航Hang*39 分钟前
WEBSTORM前端 —— 第2章:CSS —— 第3节:背景属性与显示模式
前端·css·css3·html5·webstorm
wuhen_n40 分钟前
CSS元素动画篇:基于当前位置的变换动画(一)
前端·css·html·css3·html5
前端_学习之路44 分钟前
javaScript--数据结构和算法
javascript·数据结构·算法
拉不动的猪1 小时前
# 移动端与PC端全屏的处理
前端·javascript·面试
麦麦大数据1 小时前
vue+neo4j+flask 音乐知识图谱推荐系统
vue.js·mysql·flask·知识图谱·neo4j·推荐算法·音乐推荐