如何在屏幕上移动动画js

how to move animation across the screen js

我制作了一个吃豆人张嘴和闭嘴的动画,但我也想让它在屏幕上移动。我玩过 setTimeout() ,我可以让它在屏幕上显示一个图像,但不是实际的动画。我怎样才能使用纯 JS 来做到这一点。

这是我的 HTML

<body>
  <div id="animation">
    <img id="pacManImg" src="pacMan1.png" width="50" height="50" />
    <img id="pacManImg" src="pacMan2.jpg" width="50" height="50" />
</div>
<button onclick="startAnimation()"> Start</button>
</body>

我正在为我的 js 使用它

function startAnimation() { 
  var frames = document.getElementById("animation").children;
  var frameCount = frames.length;
  var i = 0;
  setInterval(function () { 
    frames[i % frameCount].style.display = "none";
    frames[++i % frameCount].style.display = "block";
}, 300);
}

只需使用i增加left属性:

setInterval(function() {
    frames[i % frameCount].style.display = "none";
    frames[++i % frameCount].style.display = "block";
    document.getElementById("animation").style.left = i + "px";
});

请注意,这需要 position: absolute; 在您的 CSS 中。