我有一个充满网络摄像头流的 Canvas 。 最重要的是,我想让矩形(只是矩形的边框)在随机区域出现 1 秒。所以每一秒都会弹出一个矩形,下一秒就会出现在其他地方。 目前,矩形每秒出现一次,但最后一个不会消失。因此,第 2 秒有 2 个矩形,第 3 秒有 3 个矩形,等等...... 我需要找到一种方法,让矩形出现 1 秒,在 1 秒后将其移除,或者在 1 秒后移动:结果对我来说是一样的。
let sx; // x axis
let sy; // y axis
let i = setInterval( axisChanger, 1000 ); // pops up every second
function axisChanger() {
sx = getRandomInt(0, 535); // gets a random num
sy = getRandomInt(0, 445); // gets a random num
}
requestAnimationFrame(animate);
function animate(t) {
requestAnimationFrame(animate);
randomRect();
}
function randomRect() {
ctx.rect(sx, sy, 50, 30); // these 4 lines make a hollow rectangle: border only.
ctx.lineWidth = 2;
ctx.strokeStyle = '#FF0000';
ctx.stroke();
}
如果我使用 clearRect(),那么矩形的内部也将消失......因此部分网络摄像头流也随之消失。
最佳答案
如果您只需要绘制单个矩形,请将 rect()
和 stroke()
替换为 strokeRect()
:
function randomRect() {
ctx.lineWidth = 2;
ctx.strokeStyle = '#FF0000';
ctx.strokeRect(sx, sy, 50, 50);
}
当前行为的原因是 rect()
添加到主 path 并累积所有 rect()
调用。因此,必须使用 beginPath()
清除路径。
但由于您只使用一个矩形,您可以简单地使用 strokeRect()
,它不会向路径添加任何内容,而是直接呈现。
然而,替代方案是:
function randomRect() {
ctx.beginPath(); // clear path and sub-paths
ctx.rect(sx, sy, 50, 30); // these 4 lines make a hollow rectangle: border only.
ctx.lineWidth = 2;
ctx.strokeStyle = '#FF0000';
ctx.stroke();
}
关于javascript - 1 秒后隐藏 Canvas ctx.rect() - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862105/