要在Vue 3中實(shí)現(xiàn)手動(dòng)簽名的功能田度,可以結(jié)合Vue的模板和生命周期鉤子函數(shù)來實(shí)現(xiàn)妒御。下面是一個(gè)簡單的示例代碼:
<template>
<div>
<h1>手動(dòng)簽名</h1>
<canvas ref="signatureCanvas" width="500" height="200" style="border:1px solid #000000;"></canvas>
<br>
<button @click="clearCanvas">清除</button>
<button @click="saveSignature">保存</button>
</div>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0,
};
},
mounted() {
this.canvas = this.$refs.signatureCanvas;
this.context = this.canvas.getContext("2d");
this.canvas.addEventListener("mousedown", this.startDrawing);
this.canvas.addEventListener("mousemove", this.draw);
this.canvas.addEventListener("mouseup", this.stopDrawing);
this.canvas.addEventListener("mouseleave", this.stopDrawing);
},
methods: {
startDrawing(e) {
this.isDrawing = true;
this.lastX = e.offsetX;
this.lastY = e.offsetY;
},
draw(e) {
if (!this.isDrawing) return;
this.context.beginPath();
this.context.moveTo(this.lastX, this.lastY);
this.context.lineTo(e.offsetX, e.offsetY);
this.context.strokeStyle = "#000000";
this.context.lineWidth = 2;
this.context.stroke();
this.lastX = e.offsetX;
this.lastY = e.offsetY;
},
stopDrawing() {
this.isDrawing = false;
},
clearCanvas() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
saveSignature() {
const imageURL = this.canvas.toDataURL();
// 在此處可以將imageURL發(fā)送到服務(wù)器保存,或進(jìn)行其他處理
console.log(imageURL);
},
},
};
</script>
這段代碼是一個(gè)Vue組件镇饺,模板中包含了一個(gè)<canvas>元素用于繪制簽名乎莉。通過ref屬性,我們可以獲取到對(duì)應(yīng)的canvas元素奸笤,并在對(duì)應(yīng)的生命周期鉤子函數(shù)中注冊(cè)事件監(jiān)聽器惋啃。繪制簽名時(shí),在mousedown监右、mousemove和mouseup事件中調(diào)用對(duì)應(yīng)的方法來繪制路徑边灭、更新畫筆坐標(biāo)和狀態(tài)。清除按鈕調(diào)用clearCanvas方法來清除canvas內(nèi)容健盒,保存按鈕調(diào)用saveSignature方法將canvas的內(nèi)容轉(zhuǎn)為base64編碼的圖像URL并打印到控制臺(tái)绒瘦。
你可以根據(jù)需要修改saveSignature方法,以便將簽名圖像發(fā)送到服務(wù)器保存或進(jìn)行其他處理扣癣。