vue+SignaturePad H5简易电子签名,横屏适配
背景
手机端的h5页面的电子签名,横屏适配。横屏适配看了挺多,但写的都挺复杂的,自己就写了个简易的。
前提
引入signature_pad
npm install --save signature_pad
参考文章
(66条消息) vue 移动端 手写签名组件(引用signature_pad)_vue signature pad_可乐_了的博客-CSDN博客
signature_pad - npm (npmjs.com)
代码
<template> <div class="sign"> <div class="canvas-btns"> <div @click="resetCanvas">重绘</div> <div class="tip">请在虚线区域以正楷书写您的姓名</div> <div @click="finishCanvas">确认</div> </div> <canvas id="canvas"></canvas> <slot></slot> <el-button type="primary" class="btn" @click="getImgUrl">提交印章</el-button> </div> </template> <script> import SignaturePad from 'signature_pad'; export default { name: "signature", data() { return { canvas: null, signaturePad: null, config: { minWidth: 1, maxWidth: 3, penColor: "#000" }, canvasUrl: '' } }, mounted() { this.init() }, methods: { init() { this.canvas = document.querySelector("#canvas"); this.signaturePad = new SignaturePad(this.canvas, this.config); // this.canvas.height = document.body.clientHeight / 3; // this.canvas.width = document.body.clientWidth - 30; window.addEventListener("resize", this.resizeCanvas); this.resizeCanvas() // 读取数据,在canvas上显示 // this.signaturePad.fromDataURL(base64); }, // 清空 resetCanvas() { this.signaturePad.clear(); }, // 转换为图片 默认为base64 png finishCanvas() { this.canvasUrl = this.signaturePad.toDataURL() // console.log(this.signaturePad.toDataURL()); },
resizeCanvas() { console.log(window.devicePixelRatio); // let radio= Math.min(window.devicePixelRatio||1,1); // this.canvas.width = this.canvas.offsetWidth*radio; // this.canvas.height = this.canvas.offsetHeight*radio; if (document.body.clientHeight < document.body.clientWidth) { this.canvas.height = document.body.clientHeight / 2; this.canvas.width = document.body.clientWidth - 130; } else { this.canvas.height = document.body.clientHeight / 3; this.canvas.width = document.body.clientWidth - 30; } this.signaturePad.clear(); // otherwise isEmpty() might return incorrect value }, getImgUrl() { this.$emit('getImgUrl', this.canvasUrl) } }, } </script> <style lang="scss" scoped> .sign { padding-bottom: 40px; } .canvas-btns { width: 90%; padding: 10px 0; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; } .canvas-btns>div:first-child { color: red; } .canvas-btns>div:last-child { color: green; } .tip { font-size: 14px; color: #999; } .canvas-box { width: 100%; // margin: 0 auto; } #canvas { border: 1px dashed #d9d9d9; margin: 0 auto; position: relative; // position: absolute; left: 50%; transform: translateX(-50%); z-index: 999; } .btn { position: relative; left: 50%; transform: translateX(-50%); width: 90%; margin: 30px auto; } </style>