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

时间:2018-06-24 01:05:50

标签: javascript 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>

1 个答案:

答案 0 :(得分:0)

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值,有效地将它们向左移动。这样可以提高效率,因为您可以在对象离开时删除它们。您的方法需要一块大画布