基于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基礎(chǔ)知識(shí)Command對(duì)象講解2. JavaScrip簡(jiǎn)單數(shù)據(jù)類型隱式轉(zhuǎn)換的實(shí)現(xiàn)3. 解決ajax請(qǐng)求后臺(tái),有時(shí)收不到返回值的問(wèn)題4. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟5. ASP.NET MVC通過(guò)勾選checkbox更改select的內(nèi)容6. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)7. ASP中實(shí)現(xiàn)字符部位類似.NET里String對(duì)象的PadLeft和PadRight函數(shù)8. XHTML 1.0:標(biāo)記新的開(kāi)端9. jsp+mysql實(shí)現(xiàn)網(wǎng)頁(yè)的分頁(yè)查詢10. asp知識(shí)整理筆記4(問(wèn)答模式)
