翻译后无法清除 HTML 画布,使对象移动并留下痕迹



如何清除 HTML 画布,对象在第二个画布中留下灰色的痕迹?

var Xposition = 50;
var Yposition = 50;
var dx = 0.4;
var dy = 5;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#D3D3D3";
//Draw Square
function draw() {
ctx.fillStyle = "#D3D3D3";
ctx.fillRect(0, 0, 300, 300);
ctx.save();
ctx.translate(-0.2, 0);
ctx.fillStyle = "red";
ctx.fillRect(Xposition, Yposition, 20, 20);
ctx.fillStyle = "green";
ctx.fillRect(100, 0, 2, 50);
ctx.fillStyle = "green";
ctx.fillRect(200, 30, 2, 100);
Xposition += dx;

}
setInterval(draw, 10);
//Move Square
document.addEventListener('keydown', function(event) {
Xposition += 1;
if (event.keyCode == 40 && Yposition < canvas.height - 20) {
Yposition += 10;
}
//top
else if (event.keyCode == 38 && Yposition > 0) {
Yposition -= 10;
}
});
<div id="centre">
<canvas id="myCanvas" height="200px" width="300px"></canvas>
</div>

var clearAdj = 0;
//Draw Square
function draw() {
clearAdj += 0.2;
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 300 + clearAdj, 300);
ctx.save();
ctx.translate(-0.2, 0);

这是一个快速的解决方案,只需在翻译画布时添加一个调整值 画布未完全清除,因为整个 300x300 实体向左移动。您清除 300x300 空间的调用从 THAT CANVAS 的原点开始,并将随之翻译。

一个更优雅的解决方法是为每个绿色条事物制作对象,然后从中减去 x 值,有效地将它们向左移动。这将更有效,因为您可以在对象离开时删除它们。您的方法需要大画布

最新更新