繁体   English   中英

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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