Home > Article > Web Front-end > How to create frame-by-frame animation using CSS and JavaScript?
Frame-by-frame animation is a technique used in animation to create movement by displaying a series of static images that are displayed sequentially. Achieve the look of movement by displaying images in rapid succession.
Before we create frame-by-frame animation we need the following -
A series of images (frames)
Web pages using CSS and JavaScript
The process of creating frame-by-frame animation using CSS and JavaScript is relatively simple.
Step 1 – First, you need to create a series of images (frames) that you want to display continuously.
Step 1 – Next, you need to use CSS and JavaScript to create a web page that will load and display images in quick succession.
Here is a complete working code example of how to create a frame-by-frame animation using CSS and JavaScript. This code will load and display 2 images in succession.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Frame by Frame Animation</title> <style> #container { width: 400px; height: 400px; position: relative; } #container img { position: absolute; top: 0; left: 0; } </style> </head> <body> <div id="container"> <img src="https://www.tutorialspoint.com/static/images/logo-color.png" /> <img src="https://www.tutorialspoint.com/images/QAicon-black.png" /> </div> <script> var container = document.getElementById('container'); var images = container.getElementsByTagName('img'); var currentImage = 0; function changeImage() { images[currentImage].style.display = 'none'; currentImage = (currentImage + 1) % images.length; images[currentImage].style.display = 'block'; } setInterval(changeImage, 1000); </script> </body> </head>
HTML code is very simple. It consists of a div element with the id "container". There are 2 img elements inside the div element. These img elements are the frames of the animation.
CSS code sets the styles of div elements and img elements. The div element is given width and height. The img element is absolutely inside the div element.
JavaScript code is where the magic happens. First, the code gets references to the div element and the img element. Next, the code defines a variable called "currentImage". This variable will be used to keep track of the image currently being displayed.
Then the code defines a function called "changeImage". This function will hide the current image and display the next image in the sequence.
Finally, the code uses the setInterval function to call the "changeImage" function every 1000 milliseconds (1 second). This will cause images to appear in rapid succession, creating the illusion of motion.
That’s all! With just a few lines of code, you can create a simple frame-by-frame animation with CSS and JavaScript.
The above is the detailed content of How to create frame-by-frame animation using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!