废话不多说,直接上效果图&源码
代码如下
1. template
<template>
<main class="hand-sign-page">
<header class="sign-head">请在下方区域内签名header>
<div id="signContain" :style="{'--back': background}">div>
<footer class="sign-foot">
<button @click="clearCanvas">清除button>
<button @click="saveCanvas">保存button>
footer>
<img v-show="vaildSign" class="sign-img" :src="vaildSign" alt=" "/>
main>
template>
2. js
<script>
export default {
name: "hand-sign",
data() {
return {
domEl: null,//绘制canvas的父级div
canvas: null,//画布
cxt: null,//绘画环境
linewidth:1,//线条粗细,选填
color:"black",//线条颜色,选填
background:"aliceblue",//线条背景,选填
vaildSign: null
}
},
mounted() {
this.initCanvas();
},
methods: {
initCanvas() {
this.domEl = document.getElementById("signContain");
this.canvas = document.createElement("canvas");
this.domEl.appendChild(this.canvas);
this.cxt = this.canvas.getContext("2d");
this.canvas.width = this.domEl.clientWidth;
this.canvas.height = this.domEl.clientHeight;
this.cxt.fillStyle = this.background;
this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.cxt.strokeStyle = this.color;
this.cxt.lineWidth = this.linewidth;
//this.cxt.lineCap = "round";
this.clearCanvas();//先清理下
//开始绘制
this.canvas.addEventListener("touchstart", (e) => {
this.cxt.beginPath();
this.cxt.moveTo(e.changedTouches[0].pageX - e.target.offsetLeft, e.changedTouches[0].pageY - e.target.offsetTop);
}, false);
//绘制中
this.canvas.addEventListener("touchmove", (e)=> {
this.cxt.lineTo(e.changedTouches[0].pageX - e.target.offsetLeft, e.changedTouches[0].pageY - e.target.offsetTop);
this.cxt.stroke();
}, false);
//结束绘制
this.canvas.addEventListener("touchend", (e)=> {
this.cxt.closePath();
}, false);
},
//清除画布
clearCanvas() {
this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
//保存画布
saveCanvas() {
console.log(this.blankCanvas());//检查画布是否为空白
if(this.blankCanvas()) {
window.alert('请签名');
}else {
this.vaildSign = this.canvas.toDataURL();
}
},
//canvas非空验证
blankCanvas() {
let blank = document.createElement('canvas');//系统获取一个空canvas对象
blank.width = this.canvas.width;
blank.height = this.canvas.height;
return this.canvas.toDataURL() == blank.toDataURL();//比较值相等则为空
},
}
}
</script>
3. css
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)