js canvas 移动端用户可以随意画多条直线

需求:用户在页面上随意画多条直线,但是画不出直线??

clipboard.png

代码:
<!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>

阅读 3.5k
2 个回答

画直线只需要起始坐标和结束坐标就可以了,按下时的坐标作为起始坐标,手指在移动的过程中不断变换结束坐标,手指抬起时确认最终结束坐标,然后在起始坐标和结束坐标直接画直线就好了


写了个例子,不知道是不是你想要的效果,我是用的鼠标事件,你可以换成touch事件

https://codepen.io/hungtcs/pe...

你这代码别截图啊,粘贴出来才好帮你调哇

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题