Last Updated: 8th October 2025
I extend my heartfelt congratulations to the entire team behind this extraordinary achievement, successfully landing a spacecraft on a comet. This moment marks a milestone not only in space exploration but in human ingenuity. It's a proud occasion for everyone involved, especially the programmers whose tireless dedication and brilliance made this mission possible. Your relentless pursuit of excellence, through countless hours of work and problem-solving, has inspired many, including me. This article stands as a tribute to your remarkable accomplishment and the spirit of innovation that drove it.In this article, we'll explore how to create a simple yet captivating animation using HTML5 Canvas and JavaScript. While the concept is straightforward, the result is visually dynamic—we'll set up a canvas, place a couple of images on it, and bring the scene to life with smooth scrolling animation.
The first image on the canvas is the spacecraft Philae, slowly descending (animatedly) on the comet. In the background, we will animate the night sky. Later, we will make the sky roll on the canvas from right to left.
We'll add the HTML5 <canvas> element in our markup to create a space for drawing graphics. While <canvas> sets the stage, JavaScript brings it to life with animation and interactivity, most of the action happens in the <script> section.
<!doctype html> <html> <head> <title>Animation on HTML5 canvas and JavaScript</title> </head> <body> <canvas id="canvas" width="700" height="400"> Sorry. Your browser does not support HTML5 Canvas element. (encodedna.com) </canvas> </body> <script> // Initialize Canvas and Context const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const canvas_W = canvas.width; const canvas_H = canvas.height; // Start Drawing on Page Load. window.onload = () => { drawSpace(); }; // Draw Night Sky with Stars. function drawSpace() { // Fill background with black. ctx.fillStyle = '#000'; ctx.fillRect(0, 0, canvas_W, canvas_H); // Add random stars. for (let i = 0; i < 100; i++) { ctx.fillStyle = '#FFF'; const x = Math.random() * canvas_W; const y = Math.random() * canvas_H; ctx.fillRect(x, y, 2, 1); } drawImage(); } // Load and Animate Images. function drawImage() { const imgPhilae = new Image(); const imgComet = new Image(); const imgSpace = new Image(); imgPhilae.src = 'https://www.encodedna.com/html5/canvas/Philae.png'; imgComet.src = 'https://www.encodedna.com/html5/canvas/comet.png'; imgSpace.src = canvas.toDataURL(); let ve = 1; imgSpace.onload = () => { requestAnimationFrame(animateSpace); }; function animateSpace() { // Reset scroll position if needed if (ve >= canvas_W) ve = 0; ve += 1; // Scroll background ctx.drawImage(imgSpace, -ve, 0, canvas_W, canvas_H); ctx.drawImage(imgSpace, canvas_W - ve, 0, canvas_W, canvas_H); // Draw comet ctx.drawImage(imgComet, 0, 360); // Animate satellite if (ve >= 120) { ctx.drawImage(imgPhilae, 130, 270); } else { ctx.drawImage(imgPhilae, 10 + ve, 150 + ve); } requestAnimationFrame(animateSpace); } } </script> </html>
How the Script Works?
In the initial part of the script, I've defined the <canvas> element by referencing its unique ID. This is essential because a single HTML page can contain multiple canvas elements, and using the ID ensures we target the correct one for rendering. Once selected, we also retrieve its 2D drawing context, which allows us to perform graphical operations. Additionally, we access the canvas's width and height attributes to set up the drawing boundaries, ensuring that all visual elements are positioned and scaled appropriately within the defined space.
The next step involves calling the getContext() method with the string '2d', which returns a drawing context object for two-dimensional rendering. This context provides a rich set of properties and methods that enable us to create and manipulate graphics on the canvas, such as drawing images, shapes, lines, and more. While the 2D context offers extensive capabilities for building dynamic visuals and animations, this article focuses on a subset of those features relevant to our current example.
Function "drawSpace()"
The drawSpace() function is designed to create a visually engaging night sky on the canvas. It begins by filling the entire canvas area with a solid black background to simulate outer space. Then, it randomly scatters "100" small white rectangles across the canvas, representing stars twinkling in the sky. This randomized placement gives the scene a natural, dynamic feel. Once the starry backdrop is complete, the function calls drawImage() to overlay static images, such as a "satellite" and a "comet", and initiate animation.
In essence, "drawSpace()" sets the stage for the animated space scene by establishing the background and triggering the next phase of visual rendering.
Function "drawImage()"
The drawImage() function is responsible for loading and animating visual elements, specifically a satellite (Philae) and a comet, over the starry background created by drawSpace() funtion (explained above). It begins by creating Image objects for the satellite, comet, and the canvas itself (converted into an image using toDataURL).
Once the canvas image is loaded, it triggers the animateSpace() function, which continuously scrolls the background from right to left to simulate motion through space. During each animation frame, the function redraws the canvas image twice to create a seamless scrolling effect, and overlays the comet at a fixed position. The satellite is animated to move diagonally across the canvas until a certain point, after which it remains static. This function brings the scene to life by combining static imagery with dynamic motion, creating a simple yet effective space animation.
Function "animateSpace()"
The animateSpace() function creates a continuous animation loop that simulates movement through space. It starts by updating the horizontal scroll position (ve) and resets it once it reaches the canvas width to maintain a seamless loop. The background image (imgSpace) is drawn twice, once offset to the left and once to the right, to create a smooth scrolling effect.
A comet image is rendered at a fixed position, while the satellite image (Philae) is animated: it moves diagonally across the canvas until a certain scroll threshold is reached, after which it remains static. The animation is driven by requestAnimationFrame, ensuring smooth and efficient rendering with each frame.
requestAnimationFrame() Function
If you have noticed in the script, I have used requestAnimationFrame() function twice in the script. Its a built-in browser function used to create smooth and efficient animations in JavaScript. It tells the browser to execute a specified callback function just before the next screen repaint, allowing animations to sync with the display's refresh rate, typically 60 frames per second. This results in better performance and visual fluidity compared to older timing methods like setTimeout. Because it's part of the browser's native Web API, it's optimized for rendering and helps reduce CPU usage during animations.
➡️ Learn more about requestAnimationFrame() Function