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

How to clear trails when drawing rectangles on an HMTL5 canvas

本文关键字:清除 轨迹 绘制 HMTL5      更新时间:2023-09-26

我目前正在开发一个应用程序,在画布上绘制一个矩形。我可以完美地画出矩形,但当我试图改变鼠标的移动以使矩形变小时,会留下一些痕迹。当我缩小矩形的大小时,如何清除这些痕迹?下面是我使用的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();
        }         
    }
}

画布不会自行清除。至少不是像您正在使用的那样的二维上下文。如果继续在上面绘制,则新图形将放置在旧图形的顶部。你需要明确地清除它:

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

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

为了清除整个画布,您可以使用以下代码:

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

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