当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 基于canvas实现手写签名(vue)

基于canvas实现手写签名(vue)

2020年06月23日  | 移动技术网IT编程  | 我要评论

最近一直在研究canvas的东西,正好之前对手写签名这块有点兴趣。就自己基于vue写了一个简易的手写签名demo。

其中原理比较简单,先生成一个canvas画布,并对canvas进行touchstart和touchmove事件进行监听。当监听touchstart事件被触发时,我们开始触发canvas里的beginpath事件并且设置moveto原始点。当监听touchmove事件则去不断去触发lineto事件,最后stroke()。

demo里还有清除签名和保存签名的功能,分别对应了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,肯定会有很多未考虑到的地方。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网