javascript - 调用函数时如何取消绘制矩形
问题描述
我想制作一个从右向左移动的矩形。
我可以在前一个矩形的左侧绘制一个新矩形,但我无法擦除前一个矩形。
这是我的代码:
let cvs = document.getElementById("canvas");
let ctx = cvs.getContext('2d');
let firstpos = 400;
let blocks = [];
blocks[0] = {
x: 400,
y: Math.floor(Math.random() * 360)
}
function draw() {
for (var i = 0; i < blocks.length; i++) {
ctx.beginPath()
ctx.fillStyle = "white";
ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y);
ctx.fill();
blocks[i].x -= 0;
}
requestAnimationFrame(draw);
}
draw()
#canvas {
background-color: #000;
}
<canvas id="canvas" width="1000" height="500"></canvas>
解决方案
工作片段
利用CanvasRenderingContext2D.clearRect()
let cvs = document.getElementById("canvas");
let ctx = cvs.getContext('2d');
let firstpos = 400;
let blocks = [];
blocks[0] = {
x: 0,
y: Math.floor(Math.random() * 360)
}
function draw() {
blocks[0].x++;
ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas clear up
for (var i = 0; i < blocks.length; i++) {
ctx.beginPath()
ctx.fillStyle = "white";
ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y);
ctx.fill();
blocks[i].x -= 0;
}
requestAnimationFrame(draw);
}
setInterval(draw, 500)
#canvas {
background-color: #000;
}
<canvas id="canvas" width="1000" height="500"></canvas>
推荐阅读
- ruby - 如何使用块 { } 打印奇数
- flutter - Flutter:从列表中删除元素不会删除循环生成的相应UI元素
- firebase - 参数类型'String'不能分配给firebase函数上的参数类型'Uri'
- python - 在python中将列转换为dts列表
- python - 谁能启发我如何从鼠标处理程序显示具有给定 hsv 边界的跟踪矩形?
- python - Python selenium 如何处理不可交互的字段
- selenium - 如何使用 selenium 和 Python 在弹出窗口中单击“接受 cookie”按钮,当弹出窗口没有 x 时如何继续
- jwt - 从 JWT 迁移到 Identity Server 4,部署后无需重新登录网站用户
- ios - 带有 UIView 的 UIScrollView 无法选择任何子视图项
- firebase - Firestore 循环的数据插入问题