如何在屏幕js上移动动画

问题描述 投票:1回答:1

我已经创建了一个打开和关闭嘴巴的pac-man动画,但我想让它在屏幕上移动。我玩过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);
}
javascript html css html5 webpage
1个回答
2
投票

只需使用i来增加left属性:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.