前端如何实现签名功能

暗冰ཏོ 2024-10-27 11:03:01 阅读 99

1.JS实现

前端实现签名功能,通常是通过在页面上创建一个可绘制的区域,用户可以用鼠标或触摸设备进行签名。这个区域通常是一个<code><canvas>元素,结合JavaScript来处理绘制和保存签名。下面是一个简单的实现步骤:

1.1. 创建HTML页面

首先,需要在页面中添加一个<canvas>元素,用于用户签名。

<!DOCTYPE html>

<html lang="en">code>

<head>

<meta charset="UTF-8">code>

<meta name="viewport" content="width=device-width, initial-scale=1.0">code>

<title>Signature Pad</title>

<style>

canvas {

border: 1px solid #000;

width: 100%;

max-width: 600px;

height: 300px;

}

button {

margin-top: 10px;

}

</style>

</head>

<body>

<h1>Signature Pad</h1>

<canvas id="signatureCanvas"></canvas>code>

<br>

<button id="clearButton">Clear</button>code>

<button id="saveButton">Save</button>code>

<img id="savedImage" alt="Saved Signature" style="display:none;" />code>

<script src="signature.js"></script>code>

</body>

</html>

1.2. 添加JavaScript来处理签名

接下来,在signature.js中编写JavaScript代码来处理签名的绘制、清除和保存。

// 获取Canvas元素和2D绘图上下文

const canvas = document.getElementById('signatureCanvas');

const ctx = canvas.getContext('2d');

// 设定Canvas尺寸

canvas.width = canvas.offsetWidth;

canvas.height = canvas.offsetHeight;

// 初始化绘图状态

let drawing = false;

let lastX = 0;

let lastY = 0;

// 开始绘制

canvas.addEventListener('mousedown', (e) => {

drawing = true;

[lastX, lastY] = [e.offsetX, e.offsetY];

});

canvas.addEventListener('mousemove', (e) => {

if (!drawing) return;

ctx.beginPath();

ctx.moveTo(lastX, lastY);

ctx.lineTo(e.offsetX, e.offsetY);

ctx.stroke();

[lastX, lastY] = [e.offsetX, e.offsetY];

});

canvas.addEventListener('mouseup', () => drawing = false);

canvas.addEventListener('mouseout', () => drawing = false);

// 移动端支持

canvas.addEventListener('touchstart', (e) => {

drawing = true;

const touch = e.touches[0];

const rect = canvas.getBoundingClientRect();

[lastX, lastY] = [touch.clientX - rect.left, touch.clientY - rect.top];

});

canvas.addEventListener('touchmove', (e) => {

if (!drawing) return;

const touch = e.touches[0];

const rect = canvas.getBoundingClientRect();

ctx.beginPath();

ctx.moveTo(lastX, lastY);

ctx.lineTo(touch.clientX - rect.left, touch.clientY - rect.top);

ctx.stroke();

[lastX, lastY] = [touch.clientX - rect.left, touch.clientY - rect.top];

});

canvas.addEventListener('touchend', () => drawing = false);

// 清除Canvas

document.getElementById('clearButton').addEventListener('click', () => {

ctx.clearRect(0, 0, canvas.width, canvas.height);

});

// 保存签名为图片

document.getElementById('saveButton').addEventListener('click', () => {

const dataURL = canvas.toDataURL('image/png');

const img = document.getElementById('savedImage');

img.src = dataURL;

img.style.display = 'block';

});

1.3. 关键点解释

Canvas绘图:通过监听mousedownmousemovemouseup事件来检测鼠标的操作,并根据鼠标的移动轨迹在<canvas>上绘制线条。移动端支持:监听touchstarttouchmovetouchend事件,确保在触屏设备上也能绘制签名。清除签名:通过clearRect方法清除canvas的内容。保存签名:通过canvas.toDataURL()方法将签名转换为图片数据,并显示在页面上。

1.4. 额外功能

下载签名图片:可以进一步实现下载签名图片的功能,使用<a>标签和download属性。

const downloadButton = document.createElement('a');

downloadButton.href = dataURL;

downloadButton.download = 'signature.png';

downloadButton.click();

1.5. 使用库简化开发

如果需要更加复杂和完善的功能,可以使用第三方库,例如Signature Pad,它提供了更多配置和功能。

2.Vue实现

在Vue项目中实现PC端和移动端的签名功能,通常会使用<canvas>元素结合JavaScript绘图,或使用专门的签名组件库来简化实现。以下是实现签名功能的两个推荐方法:

方法 1: 手动实现签名功能(使用 <canvas>

你可以在Vue中手动实现签名功能,类似于前端原生<canvas>实现的方法。

(1) 创建签名组件

首先,创建一个Vue组件来处理签名功能。

<template>

<div>

<h2>Signature Pad</h2>

<canvas ref="signatureCanvas" class="signature-canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing" @mouseout="stopDrawing"code>

@touchstart="startDrawing" @touchmove="draw" @touchend="stopDrawing"></canvas>code>

<button @click="clearCanvas">Clear</button>code>

<button @click="saveSignature">Save</button>code>

<img v-if="savedImage" :src="savedImage" alt="Signature Image" />code>

</div>

</template>

<script>

export default {

data() {

return {

drawing: false,

lastX: 0,

lastY: 0,

ctx: null,

savedImage: null

};

},

mounted() {

const canvas = this.$refs.signatureCanvas;

canvas.width = canvas.offsetWidth;

canvas.height = canvas.offsetHeight;

this.ctx = canvas.getContext("2d");

this.ctx.lineWidth = 2;

this.ctx.strokeStyle = "#000";

},

methods: {

startDrawing(event) {

this.drawing = true;

const { x, y } = this.getMousePosition(event);

this.lastX = x;

this.lastY = y;

},

draw(event) {

if (!this.drawing) return;

const { x, y } = this.getMousePosition(event);

this.ctx.beginPath();

this.ctx.moveTo(this.lastX, this.lastY);

this.ctx.lineTo(x, y);

this.ctx.stroke();

this.lastX = x;

this.lastY = y;

},

stopDrawing() {

this.drawing = false;

},

clearCanvas() {

const canvas = this.$refs.signatureCanvas;

this.ctx.clearRect(0, 0, canvas.width, canvas.height);

},

saveSignature() {

const canvas = this.$refs.signatureCanvas;

this.savedImage = canvas.toDataURL("image/png");

},

getMousePosition(event) {

const rect = this.$refs.signatureCanvas.getBoundingClientRect();

const x = event.clientX || event.touches[0].clientX - rect.left;

const y = event.clientY || event.touches[0].clientY - rect.top;

return { x: x - rect.left, y: y - rect.top };

}

}

};

</script>

<style>

.signature-canvas {

border: 1px solid #000;

width: 100%;

max-width: 600px;

height: 300px;

}

</style>

(2)关键点

使用Vue的mounted钩子获取<canvas>上下文,并初始化绘图环境。通过mousedownmousemovemouseup等事件来处理PC端的绘图操作,同时监听touchstarttouchmove等事件处理移动端的绘图。saveSignature方法将签名保存为图片(base64格式),并在页面上显示。

方法 2: 使用第三方库 Signature Pad

Signature Pad是一个流行的JavaScript库,支持PC和移动端的签名功能,支持撤销、重做、保存等功能。可以将它集成到Vue中来简化实现。

(1) 安装 Signature Pad

首先通过npm安装 signature_pad 库:

npm install signature_pad

(2)创建Vue组件并使用Signature Pad

<template>

<div>

<h2>Signature Pad</h2>

<canvas ref="signatureCanvas" class="signature-canvas"></canvas>code>

<button @click="clearCanvas">Clear</button>code>

<button @click="saveSignature">Save</button>code>

<img v-if="savedImage" :src="savedImage" alt="Signature Image" />code>

</div>

</template>

<script>

import SignaturePad from 'signature_pad';

export default {

data() {

return {

signaturePad: null,

savedImage: null

};

},

mounted() {

const canvas = this.$refs.signatureCanvas;

canvas.width = canvas.offsetWidth;

canvas.height = canvas.offsetHeight;

this.signaturePad = new SignaturePad(canvas, {

backgroundColor: 'rgb(255, 255, 255)', // 白色背景

penColor: 'rgb(0, 0, 0)' // 黑色笔迹

});

},

methods: {

clearCanvas() {

this.signaturePad.clear();

},

saveSignature() {

if (!this.signaturePad.isEmpty()) {

this.savedImage = this.signaturePad.toDataURL('image/png');

} else {

alert("Please provide a signature first.");

}

}

}

};

</script>

<style>

.signature-canvas {

border: 1px solid #000;

width: 100%;

max-width: 600px;

height: 300px;

}

</style>

(3)Signature Pad库的优势

跨平台:支持PC端和移动端。撤销功能:你可以调用signaturePad.undo()来实现撤销功能。保存图片:提供多种格式(如PNG、JPG、SVG)来保存签名。性能优异:对于高分辨率的签名场景,提供了平滑的绘图体验。

推荐的Vue签名组件库

(1)vue-signature-pad

vue-signature-pad 是一个基于 Signature Pad 的 Vue 封装,简化了签名功能的集成和使用。

安装:

npm install vue-signature-pad

使用:

<template>

<div>

<VueSignaturePad ref="signaturePad" :options="options" />code>

<button @click="clearSignature">Clear</button>code>

<button @click="saveSignature">Save</button>code>

<img v-if="savedImage" :src="savedImage" alt="Signature Image" />code>

</div>

</template>

<script>

import VueSignaturePad from 'vue-signature-pad';

export default {

components: { VueSignaturePad },

data() {

return {

options: {

penColor: 'black',

backgroundColor: 'white'

},

savedImage: null

};

},

methods: {

clearSignature() {

this.$refs.signaturePad.clear();

},

saveSignature() {

if (!this.$refs.signaturePad.isEmpty()) {

this.savedImage = this.$refs.signaturePad.saveSignature();

} else {

alert("Please provide a signature first.");

}

}

}

};

</script>

(2)vue-canvas-signature

vue-canvas-signature 是另一个常用的签名组件,支持多种自定义选项。

 安装:

npm install vue-canvas-signature

使用:

<template>

<div>

<vue-canvas-signature ref="canvasSignature" />code>

<button @click="clearSignature">Clear</button>code>

<button @click="saveSignature">Save</button>code>

<img v-if="savedImage" :src="savedImage" alt="Signature Image" />code>

</div>

</template>

<script>

import { VueCanvasSignature } from 'vue-canvas-signature';

export default {

components: { VueCanvasSignature },

data() {

return {

savedImage: null

};

},

methods: {

clearSignature() {

this.$refs.canvasSignature.clear();

},

saveSignature() {

this.savedImage = this.$refs.canvasSignature.saveAsImage();

}

}

};

</script>

总结

手动实现签名功能 适合更灵活的场景,但需要较多的手动编写。使用 Signature Padvue-signature-pad 等库,可以简化实现,并提供更完善的功能,适用于PC端和移动端的签名需求。



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。