javascript setTimeout()不工作,图像不移动

rvpgvaaj  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(94)

我的密码是

<script>
  var theCanvas = document.getElementById("theCanvas");
  var theContext = theCanvas.getContext("2d");
  var theImage = document.getElementById("frog");
  var x = 300;
  var y = 50;
  moveProjectile();

  function drawProjectile() {
    theContext.drawImage(theImage,6,450,100,100);
  }
  function moveProjectile() {
    x += 1;
    drawProjectile();
    window.setTimeout(moveProjectile, 1000/30);
  }
</script>

我已经尝试了几种方法,包括重新定位setTimeout()并将其替换为setInterval(),但都不起作用,MDM也没有帮助。

nle07wnf

nle07wnf1#

您需要将更新后的x坐标传递给drawImage。此外,每次在下一个位置绘制图像之前,请清除画布。
(You也应该考虑使用requestAnimationFrame而不是setTimeoutsetInterval。)

const theCanvas = document.getElementById("theCanvas");
const theContext = theCanvas.getContext("2d");
const theImage = document.getElementById("frog");
let x = 0;
let y = 50;
moveProjectile();

function drawProjectile() {
  theContext.clearRect(0, 0, theCanvas.width, theCanvas.height);
  theContext.drawImage(theImage, x, y, 100, 100);
}

function moveProjectile() {
  x++;
  drawProjectile();
  window.setTimeout(moveProjectile, 1000 / 30);
}
<canvas id="theCanvas"></canvas>
<img id="frog" src="https://static.scientificamerican.com/sciam/cache/file/41DF7DA0-EE58-4259-AA815A390FB37C55_source.jpg" style="display: none;">

相关问题