如何在HTML5画布上绘制矩形时清除轨迹

时间:2015-02-12 09:16:15

标签: javascript canvas

我目前正在开发一个应用程序,我在画布上绘制一个矩形。我可以完美地绘制矩形但是当我尝试改变鼠标的移动以使矩形变小时,会留下留下的痕迹。当我将矩形的尺寸缩小时,如何清除这些轨迹?下面是我使用的JavaScript代码。提前谢谢。

 function drawSquare() {
    // creating a square
    var w = lastX - startX;
    var h = lastY - startY;
    var offsetX = (w < 0) ? w : 0;
    var offsetY = (h < 0) ? h : 0;
    var width = Math.abs(w);
    var height = Math.abs(h);

    context.beginPath();
    context.rect(startX + offsetX, startY + offsetY, width, height);
    context.fillStyle = "gold";
    context.fill();
    context.lineWidth = 1;
    context.strokeStyle = 'red';
    context.stroke();
    canvas.style.cursor = "default";
}

function getMousePos(canvas, e) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: e.pageX - canvas.offsetLeft,
        y: e.pageY - canvas.offsetTop,
    };
}

function handleMouseDown(e) {

    // get mouse coordinates
    mouseX = parseInt(e.pageX - offsetX);
    mouseY = parseInt(e.pageY - offsetY);
    // set the starting drag position
    lastX = mouseX;
    lastY = mouseY;

    isDown = true;

    if (isChecBoxClicked == true) {
        mouseIsDown = 1;
        startX = lastX;
        startY = lastY;
        var pos = getMousePos(canvas, e);

        startX = lastX = pos.x;
        startY = lastY = pos.y;

        drawSquare();

    }
    else {
        canvas.style.cursor = "default";
    }
}

function handleMouseUp(e) {
    // clear the dragging flag
    isDown = false;
    canvas.style.cursor = "default";
    // get mouse coordinates
    mouseX = parseInt(e.pageX - offsetX);
    mouseY = parseInt(e.pageY - offsetY);
    // set the starting drag position
    lastX = mouseX;
    lastY = mouseY;

    if (isChecBoxClicked == true)
    {
        canvas.style.cursor = "crosshair";

        if (mouseIsDown !== 0) {
            mouseIsDown = 0;
            var pos = getMousePos(canvas, e);
            lastX = pos.x;
            lastY = pos.y;
            drawSquare();
        }
    }
}

function handleMouseMove(e) {

    // if we're not dragging, exit
    if (!isDown) {
        return;
    }

    //if (defaultval == 1) {
    //    return;
    //}

    if (isChecBoxClicked == true) {
        canvas.style.cursor = "crosshair";

        if (mouseIsDown !== 0) {

            var pos = getMousePos(canvas, e);
            lastX = pos.x;
            lastY = pos.y;
            drawSquare();
        }         
    }
}

2 个答案:

答案 0 :(得分:1)

画布并不清晰。至少不是像您正在使用的2D上下文。如果继续使用它,新图形将放在旧图形之上。你需要明确地清除它:

context.clearRect(0, 0, canvas.width, canvas.height);

答案 1 :(得分:0)

您可能需要清除画布。如果您只是绘制正方形,则必须在drawSquare函数中执行此操作。如果你要绘制多个东西,你必须在一个更高的功能中重绘多个东西。

要清除整个画布,可以使用以下代码:

context.clearRect ( 0 , 0 , canvas.width, canvas.height );

还有很多画布库会为您管理这些并优化重绘的区域(它们可能只清除画布的一部分,因此重绘的像素更少)