Vue3 电子签名:show() 函数实现及优化
Vue3 电子签名:show() 函数实现及优化
本示例展示了在 Vue3 中使用 show() 函数实现电子签名功能,包括设置画布、画笔属性以及清空画布操作。
show() {
this.touched = false;
this.visible = true;
let that = this;
setTimeout(function () {
let canvas = that.$refs.signatureBoard;
that.boundInfo = canvas.getBoundingClientRect();
canvas.height = canvas.offsetHeight;
canvas.width = canvas.offsetWidth;
that.canvasContext = canvas.getContext('2d');
// 设置画笔线条宽度
that.canvasContext.lineWidth = 4;
// 线条连接类型
that.canvasContext.lineJoin = 'round';
// 线条末端属性
that.canvasContext.lineCap = 'round';
// 画笔线条颜色
that.canvasContext.strokeStyle = '#ff461f';
that.canvasContext.strokeStyle = 'black';
// this.canvasContext.fillRect(20, 20, 100, 100)
// this.canvasContext.fillStyle = '#00FF00'
// 画布的大小及其相对于顶点的位置
that.canvasContext.fillStyle = 'rgba(255, 255, 255, 0)';
that.canvasContext.fillRect(0, 0, that.boundInfo.width, that.boundInfo.height);
this.points = [];
}, 100);
}
该方法使用 setTimeout 延迟执行,并使用 canvas 的 getBoundingClientRect() 获取其位置和大小,确保电子签名功能的正常运作。
主要代码功能:
this.touched = false:重置 touched 状态this.visible = true:显示签名区域setTimeout(function () { ... }, 100):延迟执行代码,确保 canvas 渲染完毕后再进行操作let canvas = that.$refs.signatureBoard:获取 canvas 元素that.boundInfo = canvas.getBoundingClientRect():获取 canvas 的位置和大小canvas.height = canvas.offsetHeight; canvas.width = canvas.offsetWidth:设置 canvas 的高度和宽度that.canvasContext = canvas.getContext('2d'):获取 2D 画布上下文- 设置画笔属性:线条宽度、连接类型、末端属性、颜色
that.canvasContext.fillRect(0, 0, that.boundInfo.width, that.boundInfo.height):清空画布this.points = []:重置签名点数组
其他优化建议:
- 可以将画笔属性设置代码封装成独立的函数,提高代码可读性和可维护性
- 可以使用
requestAnimationFrame代替setTimeout,提升动画流畅度 - 可以添加对用户输入事件的监听,实现签名功能
通过以上步骤,您就可以在 Vue3 中轻松实现电子签名功能。
原文地址: https://www.cveoy.top/t/topic/p6yA 著作权归作者所有。请勿转载和采集!