先区分是PC端还是移动端,然后利用touchstart(mousedown)、touchmove(mousemove)和touchend(mouseup)来处理就可以了,重点在move那一块。 function tapClip(){ //区分PC还是手机 var hastouch = "ontouchs
function tapClip(){ //区分PC还是手机 var hastouch = "ontouchstart" in window ? true:false, tapstart = hastouch ? "touchstart":"mousedown", tapmove = hastouch ? "touchmove":"mousemove", tapend = hastouch ? "touchend":"mouseup"; //笔触圆滑 ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.lineWidth = a; ctx.strokeStyle=colors; //touchstart或者mousedown canvas.addEventListener(tapstart , function(e){ e.preventDefault(); x1 = hastouch?e.targetTouches[0].pageX-canvas.offsetLeft:e.clientX-canvas.offsetLeft; y1 = hastouch?e.targetTouches[0].pageY-canvas.offsetTop:e.clientY-canvas.offsetTop; ctx.beginPath() ctx.moveTo(x1,y1); ctx.lineTo(x1+1,y1+1); //考虑到点击时能画出一个点 ctx.stroke(); //touchmove或者mousemove canvas.addEventListener(tapmove , tapmoveHandler); //touchend或者mouseup canvas.addEventListener(tapend , function(){ canvas.removeEventListener(tapmove , tapmoveHandler); }); //move时的处理函数 function tapmoveHandler(e){ e.preventDefault() x2 = hastouch?e.targetTouches[0].pageX-canvas.offsetLeft:e.clientX-canvas.offsetLeft; y2 = hastouch?e.targetTouches[0].pageY-canvas.offsetTop:e.clientY-canvas.offsetTop; ctx.moveTo(x1,y1); ctx.lineTo(x2,y2); ctx.stroke(); x1 = x2; y1 = y2; } }) }