文章主要介绍了uni-app + vue3 手写签名的完整代码
vue代码:
<template>
<canvas canvas-id="myCanvas" class="canvas" disable-scroll="true" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" />
<cover-view class="row button-container">
<cover-view class="flex1 button" @click="clear">重写</cover-view>
<cover-view class="flex1 button margin-left-12" @click="save">提交</cover-view>
</cover-view>
</template>
<script setup>
import { useDrawSignature } from '@/hooks/index';
import { ref, unref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
onLoad(() => {});
const { isSigned, touchStart, touchMove, touchEnd, clear } = useDrawSignature('myCanvas');
const save = () => {
if (!unref(isSigned)) {
uni.showToast({
title: '请签名',
icon: 'none',
});
return;
} else {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: function (res) {
console.log(res);
console.log(res.tempFilePath);
},
});
}
};
</script>
<style scoped>
.canvas {
height: 100vh;
width: 100vw;
}
.button-container {
width: 150rpx;
height: 60rpx;
position: absolute;
bottom: 26rpx;
right: 16rpx;
}
.button {
font-size: 18rpx;
height: 26rpx;
line-height: 26rpx;
background: white;
color: #616161ff;
box-sizing: border-box;
border-radius: 20rpx;
margin-top: 2rpx;
text-align: center;
border: 1px solid #c9c9c9;
}
</style>
js代码
// 在hooks目录下,新建index.js
import { ref, unref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
export function useDrawSignature(canvasId) {
let ctx = null;
let isButtonDown = false;
let points = [];
let isSigned = ref(false);
onLoad(() => {
ctx = uni.createCanvasContext(canvasId);
// 设置画笔样式
ctx.lineWidth = 4;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
});
// 触摸开始,获取到起点
function touchStart(e) {
let startPoint = { X: e.changedTouches[0].x, Y: e.changedTouches[0].y };
points.push(startPoint); // 把起点存起来
ctx.beginPath(); // 每次触摸开始,开启新的路径
isButtonDown = true;
}
// 触摸移动,获取到路径点
function touchMove(e) {
if (isButtonDown) {
let movePoint = { X: e.changedTouches[0].x, Y: e.changedTouches[0].y };
points.push(movePoint); // 存点
let len = points.length;
if (len >= 2) {
draw(); // 绘制路径
}
}
}
// 触摸结束,将未绘制的点清空防止对后续路径产生干扰
function touchEnd() {
points = [];
isButtonDown = false;
}
// 绘画
function draw() {
let point1 = points[0];
let point2 = points[1];
points.shift();
ctx.moveTo(point1.X, point1.Y);
ctx.lineTo(point2.X, point2.Y);
ctx.stroke();
ctx.draw(true);
isSigned.value = true;
}
function clear() {
ctx.clearRect(0, 0, 1000, 1000);
ctx.draw(true);
isSigned.value = false;
}
return {
isSigned,
touchStart,
touchMove,
touchEnd,
clear,
};
}