基于canvas實現(xiàn)手寫簽名(vue)
最近一直在研究canvas的東西,正好之前對手寫簽名這塊有點興趣。就自己基于vue寫了一個簡易的手寫簽名demo。
其中原理比較簡單,先生成一個canvas畫布,并對canvas進行touchstart和touchmove事件進行監(jiān)聽。當監(jiān)聽touchstart事件被觸發(fā)時,我們開始觸發(fā)canvas里的beginPath事件并且設(shè)置moveTo原始點。當監(jiān)聽touchmove事件則去不斷去觸發(fā)lineTo事件,最后stroke()。
demo里還有清除簽名和保存簽名的功能,分別對應(yīng)了clearRect()和toDataURL()方法。
具體的demo代碼如下:
<template>
<div>
<canvas id="canvas" width="300" height="150">
</canvas>
<div class="btn">
<span @click="toClear()">清除</span>
<span @click="toSave()">保存</span>
</div>
</div>
</template>
<script>
export default {
name: "sign-name",
data(){
return {
ctx:null,
canvas:null
}
},
mounted() {
this.initPage()
},
methods:{
initPage() {
this.canvas = document.getElementById('canvas')
if(this.canvas.getContext){
this.ctx = this.canvas.getContext('2d')
let background = "#ffffff"
this.ctx.lineCap = 'round'
this.ctx.fillStyle = background
this.ctx.lineWidth = 2
this.ctx.fillRect(0,0,350,150)
this.canvas.addEventListener("touchstart",(e)=>{
console.log(123,e)
this.ctx.beginPath()
this.ctx.moveTo(e.changedTouches[0].pageX,e.changedTouches[0].pageY)
})
this.canvas.addEventListener("touchmove",(e)=>{
this.ctx.lineTo(e.changedTouches[0].pageX,e.changedTouches[0].pageY)
this.ctx.stroke()
})
}
},
toClear() {
this.ctx.clearRect(0,0,300,150)
},
toSave() {
let base64Img = this.canvas.toDataURL()
console.log(123,base64Img)
}
}
}
</script>
<style lang="scss" scoped>
.btn {
height: px2Vw(55);
position: fixed;
bottom: 0;
line-height: px2Vw(55);
border-top: px2Vw(1) solid #f7f8f9;
span {
display: inline-block;
width: px2Vw(185);
text-align: center;
}
}
canvas {
position: fixed;
border: 2px dashed #cccccc;
float: right;
}
</style>
代碼運行后的效果圖如下:


這只是個簡易的demo,肯定會有很多未考慮到的地方。demo的下載地址
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue-video-player 斷點續(xù)播的實現(xiàn)
這篇文章主要介紹了vue-video-player 斷點續(xù)播的實現(xiàn),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
使用Vant如何實現(xiàn)數(shù)據(jù)分頁,下拉加載
這篇文章主要介紹了使用Vant實現(xiàn)數(shù)據(jù)分頁及下拉加載方式。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06

