基于canvas實(shí)現(xiàn)手寫簽名(vue)
最近一直在研究canvas的東西,正好之前對(duì)手寫簽名這塊有點(diǎn)興趣。就自己基于vue寫了一個(gè)簡(jiǎn)易的手寫簽名demo。
其中原理比較簡(jiǎn)單,先生成一個(gè)canvas畫布,并對(duì)canvas進(jìn)行touchstart和touchmove事件進(jìn)行監(jiān)聽(tīng)。當(dāng)監(jiān)聽(tīng)touchstart事件被觸發(fā)時(shí),我們開(kāi)始觸發(fā)canvas里的beginPath事件并且設(shè)置moveTo原始點(diǎn)。當(dāng)監(jiān)聽(tīng)touchmove事件則去不斷去觸發(fā)lineTo事件,最后stroke()。
demo里還有清除簽名和保存簽名的功能,分別對(duì)應(yīng)了clearRect()和toDataURL()方法。
具體的demo代碼如下:
<template> <div> <canvas 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>
代碼運(yùn)行后的效果圖如下:
這只是個(gè)簡(jiǎn)易的demo,肯定會(huì)有很多未考慮到的地方。demo的下載地址
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條2. Ajax對(duì)xml信息的接收和處理操作實(shí)例分析3. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐4. Ajax返回值類型與用法實(shí)例分析5. Java實(shí)戰(zhàn)之實(shí)現(xiàn)一個(gè)好用的MybatisPlus代碼生成器6. Python request中文亂碼問(wèn)題解決方案7. python簡(jiǎn)單實(shí)現(xiàn)9宮格圖片實(shí)例8. ASP動(dòng)態(tài)include文件9. php設(shè)計(jì)模式之迭代器模式實(shí)例分析【星際爭(zhēng)霸游戲案例】10. php根據(jù)id生成10位不重復(fù)數(shù)字跟字母混合字符串
