要在Vue 3中實現手動簽名的功能,可以結合Vue的模板和生命周期鉤子函數來實現。下面是一個簡單的示例代碼:
<template>
<div>
<h1>手動簽名</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發送到服務器保存,或進行其他處理
console.log(imageURL);
},
},
};
</script>
這段代碼是一個Vue組件,模板中包含了一個<canvas>元素用于繪制簽名。通過ref屬性,我們可以獲取到對應的canvas元素,并在對應的生命周期鉤子函數中注冊事件監聽器。繪制簽名時,在mousedown、mousemove和mouseup事件中調用對應的方法來繪制路徑、更新畫筆坐標和狀態。清除按鈕調用clearCanvas方法來清除canvas內容,保存按鈕調用saveSignature方法將canvas的內容轉為base64編碼的圖像URL并打印到控制臺。
你可以根據需要修改saveSignature方法,以便將簽名圖像發送到服務器保存或進行其他處理。