实现手机手势签字功能

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

手机手势签字

效果图
相关推荐
VT.馒头6 小时前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
css趣多多6 小时前
一个UI内置组件el-scrollbar
前端·javascript·vue.js
-凌凌漆-6 小时前
【vue】pinia中的值使用 v-model绑定出现[object Object]
javascript·vue.js·ecmascript
C澒6 小时前
前端整洁架构(Clean Architecture)实战解析:从理论到 Todo 项目落地
前端·架构·系统架构·前端框架
C澒6 小时前
Remesh 框架详解:基于 CQRS 的前端领域驱动设计方案
前端·架构·前端框架·状态模式
Charlie_lll6 小时前
学习Three.js–雪花
前端·three.js
onebyte8bits7 小时前
前端国际化(i18n)体系设计与工程化落地
前端·国际化·i18n·工程化
C澒7 小时前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC7 小时前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
0思必得07 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化