当前位置 : 主页 > 网络编程 > JavaScript >

canvas实现画画(描点)

来源:互联网 收集:自由互联 发布时间:2021-06-28
先区分是PC端还是移动端,然后利用touchstart(mousedown)、touchmove(mousemove)和touchend(mouseup)来处理就可以了,重点在move那一块。 function tapClip(){ //区分PC还是手机 var hastouch = "ontouchs
先区分是PC端还是移动端,然后利用touchstart(mousedown)、touchmove(mousemove)和touchend(mouseup)来处理就可以了,重点在move那一块。
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;
        }
    })
}
网友评论