简体   繁体   中英

Cannot clear HTML canvas after translating, leaving object moving and leaving trail

How do I clear the HTML canvas, Object is leaving a trail in the second canvas where it is grey?

 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);

Here's a quick solution that just adds an adjustment value as you translate the canvas The canvas is not clearing completely because the entire 300x300 entity of moving over to the left. Your call to clear a 300x300 space starts at the origin of THAT CANVAS and will translate along with it.

A more elegant fix would be to make object for each of your green bar things and just subtract the x value from them, effectively moving them to the left. This would be more efficient as you could just delete the object as they leave. Your approach requires a large canvas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM