在画布上移动绘图

时间:2016-03-21 10:22:38

标签: javascript html5 canvas

我试图在画布上绘制一个简单的绘图板。它在电脑上工作正常。但是在手机上,我只能"画"一点,我不能拖。我不明白可能是什么问题,因为我有一个touchmove事件。

这是我的代码片段:

    canvas.addEventListener("mousedown", mouseDown, false);
    canvas.addEventListener("mousemove", mouseXY, false);
    document.body.addEventListener("mouseup", mouseUp, false);

    //For mobile
    canvas.addEventListener("touchstart", mouseDown, false);
    canvas.addEventListener("touchmove", mouseXY, true);
    canvas.addEventListener("touchend", mouseUp, false);
    document.body.addEventListener("touchcancel", mouseUp, false);

    function draw() {
        context.clearRect(0, 0, canvas.width, canvas.height); // Clears the canvas

        context.strokeStyle = "#000000";  //set the "ink" color
        context.lineJoin = "miter";       //line join
        context.lineWidth = 2;            //"ink" width

        for (var i = 0; i < clickX.length; i++) {
            context.beginPath();                               //create a path
            if (clickDrag[i] && i) {
                context.moveTo(clickX[i - 1], clickY[i - 1]);  //move to
            } else {
                context.moveTo(clickX[i] - 1, clickY[i]);      //move to
            }
            context.lineTo(clickX[i], clickY[i]);              //draw a line
            context.stroke();                                  //filled with "ink"
            context.closePath();                               //close path
        }
    }

    function addClick(x, y, dragging) {
        clickX.push(x);
        clickY.push(y);
        clickDrag.push(dragging);
    }

    function mouseXY(e) {
       if (paint) {
                addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop - 40, true);
                draw();
             }
    }

    function mouseUp() {
      paint = false;
    }

    function mouseDown(e)
    {
      var mouseX = e.pageX - this.offsetLeft;
            var mouseY = e.pageY - this.offsetTop;
            paint = true;
            addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop - 40);
            draw();
    }

1 个答案:

答案 0 :(得分:1)

问题可能是事件正在冒泡并导致移动设备出现问题。要阻止默认滚动操作,请尝试此...

function mouseXY(e) {
    e.preventDefault();
    e.stopPropagation();
    if (paint) {
        addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop - 40, true);
        draw();
    }
    return false;
}


function mouseDown(e) {
    e.preventDefault();
    e.stopPropagation();    
    var mouseX = e.pageX - this.offsetLeft;
    var mouseY = e.pageY - this.offsetTop;
    paint = true;
    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop - 40);
    draw();
    return false;
}