为什么我的画布没有正确清除?

时间:2014-11-23 00:55:47

标签: javascript html html5 canvas

我目前正在开发一个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功能是如何导致两个极点重新出现的。

您可以查看示例here。 作为参考,主要代码是:

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);

1 个答案:

答案 0 :(得分:1)

问题在于您的rect功能。具体而言,使用.rect()的{​​{1}}成员。 rect成员创建一个路径,然后用ctx填充 - 唯一的问题是,它不会关闭路径,因此它保持打开状态,并在第二次调用极点时添加到。

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

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

ctx.fillRect
相关问题