uniapp+vue3,签字功能
在uniapp+vue3环境中实现签字功能,可以使用HTML5的canvas
元素。以下是一个基本的签字组件示例:
<template>
<view class="signature-pad">
<canvas canvas-id="signature-canvas" @touchstart="startSign" @touchmove="continueSign" @touchend="endSign"></canvas>
</view>
</template>
<script setup>
import { ref } from 'vue';
const isSigning = ref(false);
const lastPoint = ref(null);
const canvas = ref(null);
const ctx = ref(null);
const startSign = (event) => {
isSigning.value = true;
const touch = event.touches[0];
const canvasRect = canvas.value.getBoundingClientRect();
const point = {
x: touch.clientX - canvasRect.left,
y: touch.clientY - canvasRect.top
};
ctx.value.beginPath();
ctx.value.moveTo(point.x, point.y);
lastPoint.value = point;
};
const continueSign = (event) => {
if (isSigning.value && lastPoint.value) {
const touch = event.touches[0];
const canvasRect = canvas.value.getBoundingClientRect();
const point = {
x: touch.clientX - canvasRect.left,
y: touch.clientY - canvasRect.top
};
ctx.value.lineTo(point.x, point.y);
ctx.value.stroke();
lastPoint.value = point;
}
};
const endSign = () => {
isSigning.value = false;
ctx.value.closePath();
};
onMounted(() => {
canvas.value = uni.createSelectorQuery().select('#signature-canvas');
canvas.value.width = 300;
canvas.value.height = 150;
ctx.value = canvas.value.getContext('2d');
ctx.value.strokeStyle = 'black';
ctx.value.lineWidth = 3;
ctx.value.lineCap = 'round';
});
</script>
<style scoped>
.signature-pad {
position: relative;
width: 300px;
height: 150px;
background-color: #fff;
}
canvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
在这个组件中,我们创建了一个canvas
元素,并在onMounted
生命周期钩子中初始化它。我们监听触摸事件来处理签名的起点、移动和终点。当用户开始签名时,我们记录下起点坐标,并开始在canvas
上绘制路径。在用户移动手指时,我们继续在canvas
上绘制线条。当用户签名结束时,我们关闭路径。
这个简单的签名组件可以满足基本的签名需求,但你可能需要添加额外的功能,比如清除签名、保存签名为图片等。
评论已关闭