簡體   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