需求:用户在页面上随意画多条直线,但是画不出直线??
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style media="screen">
*{margin: 0;padding: 0}
</style>
<script src="vue.min.js" charset="utf-8"></script>
</head>
<body>
<div id="wrap">
<canvas id="myCanvas" @touchmove='move' @touchstart='start($event)' @touchend='end'></canvas>
</div>
</body>
<script type="text/javascript">
var myCanvas='',ctx='';
var vm=new Vue({
el: '#wrap',
data: {
startposition:[],
endposition:[],
},
methods:{
startCanvas(){
myCanvas=document.getElementById('myCanvas');
myCanvas.width =document.documentElement.clientWidth;//canvas的宽度
myCanvas.height =document.documentElement.clientHeight;//canvas的高度
console.log(myCanvas.width);
//简单地检测当前浏览器是否支持Canvas对象,以免在一些不支持html5的浏览器中提示语法错误
if(myCanvas.getContext){
//获取对应的CanvasRenderingContext2D对象(画笔)
ctx = myCanvas.getContext("2d");
//线条的颜色
ctx.strokeStyle="blue";
//线条的宽度像素
ctx.lineWidth=2;
//线条的两关形状
ctx.lineCap="round";
}
},
start(e) {//获取触摸开始的 x,y
vm.startCanvas();
ctx.beginPath();
var point = {
x:e.changedTouches[0].clientX,
y:e.changedTouches[0].clientY,
}
this.startposition[0]=point;
ctx.moveTo(this.startposition[0].x, this.startposition[0].y);
},
move(e) {//获取触摸过程的 x,y
var point = {
x:e.changedTouches[0].clientX,
y:e.changedTouches[0].clientY,
}
this.endposition[0]=point;
ctx.lineTo(this.endposition[0].x, this.endposition[0].y);
ctx.stroke();
},
end(e) {//触摸结束
ctx.closePath();
},
draw() {//画线
ctx.moveTo(this.startposition[0].x, this.startposition[0].y);
ctx.lineTo(this.endposition[0].x, this.endposition[0].y);
ctx.stroke();
ctx.closePath();
},
},
});
</script>
</html>
画直线只需要起始坐标和结束坐标就可以了,按下时的坐标作为起始坐标,手指在移动的过程中不断变换结束坐标,手指抬起时确认最终结束坐标,然后在起始坐标和结束坐标直接画直线就好了
写了个例子,不知道是不是你想要的效果,我是用的鼠标事件,你可以换成touch事件
https://codepen.io/hungtcs/pe...