一、实现效果
二、实现原理
- 创建画布和基本样式。
<view class="box">
<canvas canvas-id="writeText" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"
style="width: 400px;height: 300px;"></canvas>
<view class="btn-box">
<view class="clear-btn btn" @click="clearDraw">清除标签</view>
<view class="save-btn btn" @click="saveDraw">保存标签</view>
</view>
</view>
let ctx=null
onLoad() {
ctx = uni.createCanvasContext('writeText');
}
2. 监听鼠标按下@mousedown事件,开启绘画isDrawing变true,存储当前点击距离元素左上角的x,y轴。
startDrawing(e) {
this.isDrawing = true;
this.siteX = e.pageX - e.target.offsetLeft;
this.siteY = e.pageY - e.target.offsetTop;
}
3. 监听鼠标移动@mousemove,当isDrawing为false时,结束监听。监听到鼠标最后移动的位置,将mousedown下的坐标当做起始点,mousemove下的做为结束点,绘制线条,使用stroke和draw方法绘制,更新坐标进行下次使用。
draw(e) {
if (!this.isDrawing) return;
let lastX = e.pageX - e.target.offsetLeft;
let lastY = e.pageY - e.target.offsetTop;
ctx.beginPath();
ctx.moveTo(this.siteX, this.siteY);
ctx.lineTo(lastX, lastY);
ctx.stroke();
ctx.draw(true);
this.siteX = lastX;
this.siteY = lastY;
}
4.监听@mouseup,当鼠标弹起,移动鼠标不再绘制。
stopDrawing() {
this.isDrawing = false;
}
5. 最后是清除画布和保存画布,通过点击按钮进行操作
clearDraw() {
ctx.clearRect(0, 0, 400, 300)
ctx.draw()
}
saveDraw() {
uni.canvasToTempFilePath({
x: 0,
y: 0,
width: 400,
height: 300,
canvasId: 'writeText',
success: function(res) {
let image = res.tempFilePath;
let link = document.createElement("a");
link.download = "signature.png";
link.href = image;
link.click();
}
})
}
三、总结
canvas数字签名到这里就结束了,需要查看完整代码,下方git仓库克隆自行学习。 gitee.com/gomigo/miko…