vue+canvas 移动端 签名实现

直接上代码

html

<template>
	<div class="canvas">
	        <canvas
	          ref="canvasF"
	          class="myCanvas"
	          @touchstart="touchStart"
	          @touchmove="touchMove"
	          @touchend="touchEnd"
	        ></canvas>
	        <img class="imgCanvas" :src="imgUrl" />
	</div>
	 <div class="buttom">
	 			 < class="buttoms" type="primary" @click="clear">重签</button>
	        	< class="buttoms" type="primary" @click="save">提交</button>
	</div>
</template>

vue.js

export default {
	data() {
	    return {
	      //所需
	      imgUrl: "", //保存为图片
	      canvasTxt: null,
	      startX: 0,
	      startY: 0,
	      moveY: 0,
	      moveX: 0,
	      canvas: ""
	    }
	  },
	 //在这里获取canvas的dom,并设置画布
	mounted() {
	    this.$nextTick(() => {
	      let canvas = this.$refs.canvasF;
	      this.canvas = this.$refs.canvasF;
	       canvas.height='400';  
	       canvas.width='400';
	      this.canvasTxt = canvas.getContext("2d");
	    });
	  },
	  //点击时设置起点
	  touchStart(ev) {
	      var ev = ev || event;
	      ev.preventDefault();
	      let obj = {
	        x: ev.targetTouches[0].clientX - this.canvas.offsetLeft,
	        y: ev.targetTouches[0].clientY - this.canvas.offsetTop
	      };
	      this.startX = obj.x;
	      this.startY = obj.y;
	      this.canvasTxt.beginPath();
	      this.canvasTxt.moveTo(this.startX, this.startY);
	      this.canvasTxt.lineTo(obj.x, obj.y);
	      this.canvasTxt.stroke();
	      this.canvasTxt.closePath();
    },
    //移动时绘制线条
    touchMove(ev) {
      var ev = ev || event;
      ev.preventDefault();
      let obj = {
        x: ev.targetTouches[0].clientX - this.canvas.offsetLeft,
        y: ev.targetTouches[0].clientY - this.canvas.offsetTop
      };
      this.moveY = obj.y;
      this.moveX = obj.x;
      this.canvasTxt.beginPath();
      this.canvasTxt.moveTo(this.startX, this.startY);
      this.canvasTxt.lineTo(obj.x, obj.y);
      this.canvasTxt.stroke();
      this.canvasTxt.closePath();
      this.startY = obj.y;
      this.startX = obj.x;
    },
    //结束
    touchEnd(ev) {
      ev.preventDefault();
      this.canvasTxt.closePath();
    },
     //清空 画布
    clear() {
      this.canvasTxt.clearRect(0,0,this.$refs.canvasF.width,this.$refs.canvasF.height);
    },
       //保存为图片
    save() {
      this.imgUrl = this.$refs.canvasF.toDataURL();
      console.log(this.$refs.canvasF.toDataURL()); //签名img回传后台
    },
 }

canvas的宽高一定要设置好,不然。。。。。。。
this.$nextTick(()=>{}) 看情况使用

css

.canvas {
  color: #000;
  padding: 5px;
}
.myCanvas {
  background: #fff;
}

css自己看着办呗

可能你会使用这个 getBoundingClientRect() 来进行鼠标的定位。但是呢,这个用来设置定位可能会定位偏移,所以谨慎使用!(其实是canvas的宽高没设好)

以上 。。。。。。

展开阅读全文
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读