Animating an image using JavaScript

This tutorial shows how to animate (move) an image across the screen. You can combine the code with other code from previous tutorials such as the one on timed image swapping to also get images to swap while they are moving (eg. you could use two images for a character with legs in different positions, so as the images swap it looks like the character is running).

You will need an image to use in your animation. Keep the image file in the same folder as your HTML file. In the sample code below, the image’s file name is image.png (a PNG image file). Start and stop buttons have also been added to start/stop the animation. This is what the animation will look like:


Refer to the comments in the code below to find out what is happening on each line.

<title>JavaScript Image Animation</title>
<script type="text/javascript">
var imgObj ;
var animate ;
function init(){
 imgObj = document.getElementById('myImage'); 'relative'; = '0px'; 
function moveRight(){ = parseInt( + 5 + 'px'; // move from the left 5 pixels
 animate = setTimeout(moveRight,20); // call moveRight in 20 milliseconds
function stop(){
 clearTimeout(animate); // stops the animation
 // add = '0px'; if you want to reset the image back to the left side of screen
window.onload =init; // starts animation when page loads
<img id="myImage" src="image.png" width="100" height="100"/>
<p>Click the buttons below to start and stop the animation.</p>
<input type="button" value="Play" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />

Next tutorial: Keyboard events in JavaScript