为什么我的画布无法正确清除

Why is my canvas not clearing correctly?

本文关键字:清除 布无法 我的 为什么      更新时间:2023-09-26

我目前正在用HTML5 Canvas做一个小的实验项目。

基本上,目前我只是想让画布按预期清晰。我的代码目前唯一要做的就是生成一个中间断开的行。但是,目前我正在尝试制作一行,然后删除该行并在另一个不同位置添加另一行而不显示第一行。

我认为这段代码会起作用:

poles(20); // this number is the x position at which the line (pole) will be generated
ctx.clearRect(0, 0, WIDTH, HEIGHT);
poles(140)

从技术上讲,这应该只显示第二个极点,因为在生成第一个极点后应该已经清除了画布。但命中仍然显示了两者。

当我只尝试时:

poles(20);
ctx.clearRect(0, 0, WIDTH, HEIGHT);

画布是空白的,这告诉我清理工作正常。

我又尝试了一件事:

poles(20);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
setTimeout(function () {
    poles(140)
}, 1000);

在这种情况下,两个极点都出现了,但直到 1 秒后才出现,这告诉我 poles 函数导致再次生成这两个极点,即使函数没有循环:

function poles(x) {
    var bottomH = getRandomInt(20, 180)
    // using seperate rectangles will make a break
    rect(40, 220 - bottomH, x, 0); // first section of line
    rect(40, bottomH, x, HEIGHT - bottomH); // second section of line        
}

我希望有人能向我解释为什么我的poles函数会导致两极重新出现。

您可以在此处查看示例。作为参考,主代码为:

var canvas = document.getElementById("canvas"),
    WIDTH = canvas.width,
    HEIGHT = canvas.height;
var ctx = canvas.getContext("2d");
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function rect(w, h, x, y) {
    ctx.rect(x, y, w, h);
    ctx.fill();
}
function poles(x) {
    var bottomH = getRandomInt(20, 180); // determine where the line break will be
    rect(40, 220 - bottomH, x, 0);
    rect(40, bottomH, x, HEIGHT - bottomH);
}
poles(20);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
setTimeout(function () {
    poles(140)
}, 1000);

问题出在您的rect函数上。具体来说,随着ctx .rect()成员的使用. rect 成员创建一个路径,然后用ctx.fill()填充该路径 - 唯一的问题是,它不会关闭路径,因此它保持打开状态,并在第二次调用极点时添加。

您可以在退出 rect 函数之前关闭路径,或者更简单地说,通过使用 ctx.fillRect 在单个调用中定义和填充矩形来完全避免路径。

以下更改使代码按预期运行:

function rect(w, h, x, y) 
{
//    ctx.rect(x, y, w, h);
//    ctx.fill();
    ctx.fillRect(x,y,w,h);
}