赞
踩
电子签名在现代Web应用中越来越普遍,例如合同签署、确认表单等。本文将介绍如何使用Vue.js实现一个简单的电子签名功能,并将签名生成图片。
项目结构如下:
my-vue-signature/
├── public/
│ └── index.html
├── src/
│ ├── components/
│ │ └── SignaturePad.vue
│ ├── App.vue
│ ├── main.js
├── package.json
└── README.md
我们将使用一个轻量级的签名画布库 signature_pad
,通过npm安装:
如果想学习signature_pad
点击链接 - signature_pad 库详解
npm install signature_pad
在 src/components
文件夹下创建 SignaturePad.vue
文件:
<template> <div> <canvas ref="signatureCanvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="endDrawing" @mouseleave="endDrawing"></canvas> <button @click="clearCanvas">清除</button> <button @click="saveSignature">保存签名</button> </div> </template> <script> import SignaturePad from 'signature_pad'; export default { name: 'SignaturePad', data() { return { signaturePad: null, isDrawing: false, }; }, mounted() { const canvas = this.$refs.signatureCanvas; canvas.width = 600; canvas.height = 300; this.signaturePad = new SignaturePad(canvas); }, methods: { startDrawing() { this.isDrawing = true; this.signaturePad.beginPath(); }, draw(event) { if (!this.isDrawing) return; const rect = this.$refs.signatureCanvas.getBoundingClientRect(); this.signaturePad.lineTo(event.clientX - rect.left, event.clientY - rect.top); this.signaturePad.stroke(); }, endDrawing() { this.isDrawing = false; this.signaturePad.closePath(); }, clearCanvas() { this.signaturePad.clear(); this.$emit('clean') }, saveSignature() { if (this.signaturePad.isEmpty()) { alert('请先签名!'); return; } const dataURL = this.signaturePad.toDataURL(); this.$emit('save-signature', dataURL); }, }, }; </script> <style scoped> canvas { border: 1px solid #ccc; display: block; margin-bottom: 10px; } button { margin-right: 10px; } </style>
<template> <div id="app"> <div class="center"> <h1>电子签名</h1> <SignaturePad @save-signature="handleSaveSignature" @clean="handleClean" /> <div > <h2>签名图片:</h2> <div class="showimg"> <img v-if="signatureImage" :src="signatureImage" alt="Signature" /> </div> </div> </div> </div> </template> <script> import SignaturePad from './components/SignaturePad.vue'; export default { name: 'App', components: { SignaturePad, }, data() { return { signatureImage: null, }; }, methods: { handleSaveSignature(dataURL) { this.signatureImage = dataURL; }, handleClean(){ this.signatureImage = null } }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; text-align: center; margin-top: 60px; display: flex; justify-content: center; align-items: center; flex-direction: column } .center{ } .showimg{ border-radius: 4px; border: 1px solid #ccc; padding: 10px; box-sizing: border-box; width: 610px; height: 310px; } </style>
通过本文,你学习了如何使用Vue.js和 signature_pad
库实现一个简单的电子签名功能,并生成签名图片。通过这种方式,可以轻松地在Web应用中集成电子签名功能,提高用户体验。
希望本文能帮助你实现电子签名功能。如果有任何问题或建议,请随时联系。祝你开发顺利!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。