【问题标题】:How to undraw the a rectangle when recalling a function [duplicate]调用函数时如何取消绘制矩形[重复]
【发布时间】:2020-02-27 20:52:22
【问题描述】:
我想制作一个从右向左移动的矩形。
我可以在前一个矩形的左侧绘制一个新矩形,但我无法擦除前一个矩形。
这是我的代码:
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>
【问题讨论】:
标签:
javascript
html5-canvas
【解决方案1】:
工作sn-p
利用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>
【解决方案2】:
不可能在画布中“取消绘制”某些东西。但是,您可以使用clearRect 清除每一帧上的画布,然后在新位置重新绘制所有内容。
此外,当前代码使用blocks[i].x -= 0;,即使清除和重绘也不会改变动画状态。
fillRect 的参数显示不正确或标签错误。 ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y); 应该是 ctx.fillRect(blocks[i].x, blocks[i].y, width, height);。也不需要为此方法创建路径或调用fill。
通常将块的所有数据封装在对象内。我们需要颜色、速度和 x/y/高度/宽度。
请注意,y: Math.floor(Math.random() * 360) 可能导致高度为零。
这是一个在画布上移动块的简单示例:
const cvs = document.getElementById("canvas");
cvs.width = innerWidth;
cvs.height = innerHeight;
const ctx = cvs.getContext("2d");
const blocks = [{
x: innerWidth - 50,
y: 20,
velocityX: -1,
width: 50,
height: 50,
color: "white"
}];
(function draw() {
ctx.clearRect(0, 0, cvs.width, cvs.height);
for (const block of blocks) {
ctx.fillStyle = block.color;
ctx.fillRect(block.x, block.y, block.width, block.height);
block.x += block.velocityX;
}
requestAnimationFrame(draw);
})();
#canvas {
background-color: #000;
}
<canvas id="canvas"></canvas>