Reputation: 55
I've created an animation of a pac-man opening and closing its mouth, but i would like to have it move across the screen as well. I've played around with setTimeout() and i can get it one image to go across the screen but not the actual animation. how can i do this using pure JS.
this is the HTML i have
<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>
i'm using this for my 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);
}
Upvotes: 1
Views: 1112
Reputation: 44087
Just use i
to increase the left
property:
setInterval(function() {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
document.getElementById("animation").style.left = i + "px";
});
Note that this requires position: absolute;
in your CSS.
Upvotes: 2