<canvas
ref="myCanvas"
:width="styleWidth"
:height="styleHeigth"
></canvas>
<script>
this.canvasKeep = this.$refs.myCanvas;
this.ctx = this.canvasKeep.getContext("2d");
this.styleWidth = this.$refs.canvasWidth.offsetWidth * 0.98;
this.styleHeigth = this.$refs.canvasWidth.offsetHeight * 0.8;
this.l = this.$refs.canvasWidth.getBoundingClientRect().left; //距离左边距离
this.t = this.$refs.myCanvas.getBoundingClientRect().top; //距离顶部距离
//监听触摸开始
this.canvasKeep.addEventListener("touchstart", e => {
this.start_x = e.touches[0].pageX - this.l;
this.start_y = e.touches[0].pageY - this.t;
console.log(
this.l,
"===>",
e.touches[0].pageX,
"||",
this.t,
"==>",
e.touches[0].pageY
);
//开始本次绘画
this.ctx.beginPath();
//画笔起始点
this.ctx.moveTo(this.start_x, this.start_y);
//显示坐标
this.postion = `${this.start_x},${this.start_y}`;
});
//监听触摸滑动
this.canvasKeep.addEventListener("touchmove", e => {
this.move_x = e.touches[0].pageX - this.l;
this.move_y = e.touches[0].pageY - this.t;
//根据鼠标路径绘画
this.ctx.lineTo(this.move_x, this.move_y);
console.log(this.move_x, this.move_y);
//立即渲染
this.ctx.stroke();
//显示坐标
this.postion = `${this.start_x},${this.start_y}`;
});
//监听触摸结束
this.canvasKeep.addEventListener("touchend", e => {
this.end_x = e.changedTouches[0].pageX - this.l;
this.end_y = e.changedTouches[0].pageY - this.t;
console.log(this.end_x, this.end_y);
//创建从当前点到开始点的路径
this.ctx.closePath();
//显示坐标
this.postion = `${this.start_x},${this.start_y}`;
});
</script>