Home/Blog/Programming/Get started with Canvas animations in JavaScript
Canvas animations JavaScript
Home/Blog/Programming/Get started with Canvas animations in JavaScript

Get started with Canvas animations in JavaScript

10 min read
May 19, 2025
content
What is Canvas?
The <canvas> element
The canvas context
How to draw shapes on the canvas (lines, rectangles, circles)
Example: Drawing a line
Example: Drawing a rectangle
Example: Drawing a circle
How to animate shapes using JavaScript
How to animate multiple objects
Why requestAnimationFrame() is better for smooth animations
Why use requestAnimationFrame() instead of setInterval()?
Wrapping up
Continue reading about JavaScript and game development

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Key takeaways:

  • The HTML5 canvas provides a pixel-based space for drawing, allowing for precise and dynamic graphics rendering.

  • Utilizing the 2D context is crucial—it acts as a toolkit for setting drawing attributes and rendering shapes, text, and images.

  • Since the canvas renders drawings directly as pixels, each frame must be redrawn to animate objects, similar to a stop-motion effect.

  • Optimizing animations involves clearing previous frames and using browser-friendly methods like requestAnimationFrame for smoother motion compared to setInterval.

Want to build your own browser game but feel stuck at step one? Mastering Canvas animations is the perfect starting point.

“Animation is not the art of drawings that move but the art of movements that are drawn.” — Norman McLaren

In this guide, you’ll learn to draw and animate objects using HTML5 canvas and JavaScript, the skills that unlock everything from simple graphics to interactive games.

Learn JavaScript

Cover
Learn to Code: Javascript for Absolute Beginners

JavaScript is a versatile language essential for web development, working alongside HTML and CSS to build both simple and complex web applications. This course offers a comprehensive introduction to JavaScript for beginners, starting with fundamental concepts like problem-solving and simple JavaScript programs. Through interactive exercises, challenges, and quizzes, learners will master control structures, loops, strings, arrays, and functions. By the end of this course, you'll have solid problem-solving skills, a deep understanding of JavaScript programming, and practical experience in writing clean, efficient code. This knowledge will prepare you for a successful career as a JavaScript developer and significantly enhance your employability in the tech industry.

8hrs
Beginner
4 Challenges
4 Quizzes

What is Canvas?#

Apple first introduced Canvas in 2004 to enhance applications and the Safari browser. Later, the WHATWGWeb Hypertext Application Technology Working Group standardized it. Canvas offers fine-grained control over rendering, but this comes with the responsibility of manually managing every detail. Essentially, it can handle numerous objects, but we need to code everything explicitly.

The canvas uses a 2D drawing context for rendering shapes, text, images, and other objects. The process is similar to choosing a color and brush before painting. We can change these attributes before each new drawing or continue with the existing ones.

Canvas offers fine-grained control over rendering, but this comes with the responsibility of managing every detail manually. It’s a “fire-and-forget” system—once you’ve drawn something, it’s remembered as pixels, not as an object you can directly manipulate. So, if you want to move an object, you need to redraw it in a new position.

Animating on Canvas is similar to creating a stop-motion film. Each frame requires subtly shifting the objects to create the illusion of movement.

The <canvas> element#

The HTML <canvas> element is an HTML5 tag that provides a blank container on which we can draw graphics. We can draw shapes and lines using the anvas API, which facilitates graphic rendering via JavaScript. Unlike SVG, which is vector-based, canvas works with pixels, making it more suitable for complex graphics and animations.

A canvas is a rectangular area on an HTML page that, by default, lacks a border or content. Its default width size is 300 pixels, and its height size is 150 pixels, but we can customize this using the HTML height and width properties:

<canvas id="canvas" width="600" height="300"></canvas>
Creating the HTML5 Canvas element with a specified width and height

This creates a blank canvas of 600×300600\times 300 pixels, ready to be used with JavaScript.

The id attribute is crucial for referencing the canvas from your script. To add a border, use the style attribute or CSS with the class attribute:

Adding a border to the canvas and a “Play” button to trigger the animation

With the border in place, you can see the dimensions of your empty canvas on the screen. The button includes an onclick event that triggers the animate() function when clicked.

JavaScript code typically resides within <script> elements placed in the <body> of your document, ideally after the <canvas> element:

<script type="text/javascript" src="canvas.js"></script>
Including the JavaScript file containing the canvas animation code

You can obtain a reference to the HTML <canvas> element in the DOM (Document Object Model) using the getElementById() method:

const canvas = document.getElementById('canvas');
Getting a reference to the canvas element

Now, you have access to the canvas element, but you can’t draw on it directly. Instead, you need to use one of its rendering contexts.

The canvas context#

The canvas’s 2D context lets us draw shapes, text, images, and more. Start by selecting a color and brush and then “paint.” We can switch these attributes before each new drawing or continue with the current ones.

The HTMLCanvasElement.getContext() method returns a drawing context, which is where we render the graphics. Using '2d' as the argument provides the 2D rendering context:

const ctx = canvas.getContext('2d');
Getting a reference to the canvas 2D rendering context

There are other contexts available, such as webgl for 3D rendering, but they are beyond the scope of this tutorial.

The CanvasRenderingContext2D object offers various methods for drawing lines and shapes. We can set the line color using strokeStyle and the thickness using lineWidth:

ctx.strokeStyle = 'black';
ctx.lineWidth = 5;
Setting the stroke style (color) and line width for drawing

Now, you’re ready to draw your first line on the canvas. But first, you need to understand how the canvas interprets drawing positions. The HTML canvas is a two-dimensional grid. The upper-left corner has the coordinates (0, 0).

X →
Y [(0,0), (1,0), (2,0), (3,0), (4,0), (5,0)]
↓ [(0,1), (1,1), (2,1), (3,1), (4,1), (5,1)]
[(0,2), (1,2), (2,2), (3,2), (4,2), (5,2)]
Representation of a two-dimensional grid in canvas

So, moveTo(4, 1) means starting at the upper-left corner (0,0) and moving four columns to the right and one row down.

How to draw shapes on the canvas (lines, rectangles, circles)#

We can draw different shapes, such as rectangles, circles, and lines, using the Canvas API.

Example: Drawing a line#

The lineTo() method adds a straight line to the current sub-path, connecting its last point to the specified (x, y) coordinates. Like other path modification methods, lineTo() doesn’t render anything directly. To draw the path, use the fill() or stroke() methods.

Drawing a line on the canvas

This draws a black line from canvas point (100, 50) to canvas point (300, 150).

Example: Drawing a rectangle#

We can use fillRect() to draw a filled rectangle. The fillStyle property determines the fill color:

Drawing a filled blue rectangle

This will draw a filled blue rectangle.

Example: Drawing a circle#

We can use the arc() method of the 2D rendering context. The ctx.beginPath() is essential. It starts a new path. If we don’t begin a new path, the arc() method might connect to a previous path, creating unexpected results. Here’s a breakdown of how it works:

  • ctx.arc(): This is the core of drawing the circle. It has the following parameters:

    • centerX: The x-coordinate of the circle’s center.

    • centerY: The y-coordinate of the circle’s center.

    • radius: The radius of the circle

    • startAngle: The starting angle of the arc, in radians. 0 radians corresponds to the 3 o’clock position.

    • endAngle: The ending angle of the arc, in radians. To draw a full circle, use Math.PI * 2 (which is 360 degrees in radians).

    • anticlockwise: A boolean value. false (the default) draws the arc clockwise. true draws it counterclockwise. For a normal circle, we’ll usually use false or omit this parameter.

  • ctx.fillStyle: This sets the fill color of the circle. If we don’t set a fill style, the circle won’t be filled.

  • ctx.fill();: This fills the circle with the currently set fillStyle.

The ctx.closePath() is not strictly required for a circle; it’s good practice to close the path, especially if we’re going to be drawing more shapes afterward.

Drawing a filled red circle

Now we’ve got a red circle. Simple, right? The key is understanding how Canvas interprets coordinates—where (0,0) is the top-left corner.

How to animate shapes using JavaScript#

Let’s animate the blue square. We’ll add a “Play” button and define a function animate() and call it to start the animation on the button click.

Start by setting the square’s size to 30. Then, in the animate() function, increment the x value in steps of size and redraw the object repeatedly. The following code moves the block to the right edge of the canvas:

Initial attempt to animate a square

This draws the square, but we have two problems:

  1. We’re not cleaning up the previous frame.

  2. The animation is too fast.

We need to erase the old block before drawing the new one. The clearRect() erases pixels within a specified rectangular area. Using the canvas’s width and height allows us to clear it completely between draws.

Clearing the canvas with clearRect() before each draw to prevent overlapping

This will clear the previous frames.

Now, let’s slow down the animation using setInterval(function, delay). This function repeatedly executes the specified function every delay milliseconds. Setting the interval to 200 ms means the code runs five times per second.

Animating the square using setInterval() to repeatedly update and redraw it

The clearInterval() stops the timer created by setInterval(). It takes the identifier returned by setInterval() as an argument. Now, clicking the “Play” button will animate the square from left to right.

Common Pitfall: Clicking the “Play” button multiple times causes overlapping animations. This happens because each click creates a new interval, resulting in multiple animations running independently. The solution? Manage all animations within a single loop to avoid chaos.

If you’re ready to dive even deeper into the world of HTML5 canvas, consider taking your skills to the next level. The “HTML5 Canvas From Noob to Ninja: An Interactive Deep Dive” course on Educative offers a comprehensive exploration of canvas—from advanced drawing techniques to optimizing animations for game development. This interactive course provides hands-on challenges and real-world projects that will help you unlock the full potential of Canvas.

Cover
HTML5 Canvas: From Noob to Ninja - an interactive deep dive

Kirupa is an MIT grad who works at Microsoft as Senior Program Manager. He has been tinkering with web technologies since 1998. He works on the Edge browser team where he gets to sink his teeth into the cutting-edge web technologies. HTML5 is taking over the browsers and one of the coolest things in HTML5 is the canvas - the immediate mode drawing surface you have in HTML for bringing pixels to life using JavaScript. It is used to create games, graphs, and animations. This is an extensive course with interactive playgrounds (so you don't have to install anything). The course can be divided into four parts. 1. Understand basics of Canvas and compare it with DOM. 2. Learn how to draw shapes. 3. Take a deep dive into canvas transformations and animations. 4. Explore advanced mouse and keyboard handling to create truly interactive applications using canvas. If none of what I just wrote makes sense, then the content here is just what you need 😀 . Let's get started.

9hrs
Beginner
62 Playgrounds
109 Illustrations

How to animate multiple objects#

To animate multiple blocks smoothly, we need to rethink our approach. Instead of giving each block its setInterval(), we should manage the moving objects before drawing them all at once.

We can use a started variable to ensure setInterval() only starts on the first button click. Each button click adds a new x-coordinate (starting at 0) to a squares array. For more complex scenarios, creating a Square object with coordinates and other properties (like color) would be more appropriate.

Managing multiple animated squares using an array and a single setInterval()

The tick() function now clears the screen and paints all objects in the squares array every 200 ms. Using a single interval avoids the flickering issue.

Why requestAnimationFrame() is better for smooth animations#

Another animation technique is requestAnimationFrame(). This function tells the browser you want to perform an animation and requests it to call a specific function to update the animation before the next repaint. It’s like saying, “Browser, next time you’re about to paint, also run this function so I can update my animation.”

To animate with requestAnimationFrame(), create a function that paints a frame and then schedules itself to run again. This creates an asynchronous loop that executes when the canvas is redrawn.

Using requestAnimationFrame() for smoother, browser-optimized animation

If you play this, you’ll notice the animation is visible (unlike with setInterval()) and incredibly smooth. The callback typically executes 60 times per second.

The requestAnimationFrame() returns an ID that we can use to cancel the scheduled animation frame with cancelAnimationFrame(id).

To control the animation speed, we can use a timer to track the elapsed time since the last tick() call. The callback function receives a DOMHighResTimeStamp argument, indicating when requestAnimationFrame() started executing callbacks.

Controlling the animation speed using the timestamp parameter of requestAnimationFrame().

This achieves the same functionality as the earlier setInterval() example.

Why use requestAnimationFrame() instead of setInterval()?#

  • It enables browser optimizations.

  • It manages the frame rate automatically.

  • Animations only run when the page is visible.

Wrapping up#

In this blog, you created an HTML5 canvas and drew on it using JavaScript and its 2D rendering context. You also explored some of the available canvas context methods and rendered various shapes.

You then animated multiple objects, learning how to use setInterval() to create an animation loop that manages and draws objects. Finally, you learned how to optimize animations with requestAnimationFrame().

Now that you understand basic Canvas animations, you’ve taken your first steps into game development! Your next challenge is to tackle a beginner-friendly game development project to learn about:

  • Designing gameplay loops

  • Implementing interactive controls with addEventListener

  • Detecting object collisions

  • Score tracking

To help you on this journey, we recommend checking out the “Game Development with JavaScript: Creating Tetris” course. This course will teach you to apply your frontend JavaScript skills to build your first game. By creating Tetris, you’ll learn game development fundamentals and build a project for your portfolio.

Cover
Game Development with JavaScript: Creating Tetris

In this course, you will get hands-on game development experience with JavaScript. Using the classic game of Tetris, you are going to cover concepts like graphics, game loops, and collision detection. By the end of this course, we will have a fully functioning game with points and levels. Try it out with your friends and put it in your portfolio for employers to see.

5hrs 30mins
Beginner
12 Playgrounds
10 Quizzes

Happy learning!

Continue reading about JavaScript and game development#

Now, challenge yourself: can you animate a bouncing ball or create simple collision detection? These small projects will build your confidence and prepare you for full-scale game development.


Frequently Asked Questions

How to create a moving animation in JavaScript?

A moving animation in JavaScript can be made easily using a combination of setInterval and clearInterval functions. The animation logic is encapsulated within a function, which is then passed as an argument to setInterval, along with the desired interval duration for the animation to replay. The clearInterval function can be called when the animation is to be stopped. For example, to create a moving box, the left and top attributes of the box can be updated by 5 px at an interval of 50-milliseconds using the code below:

const intervalId = setInterval(() => {
  positionX += 5; positionY += 5;
  box.style.left = positionX + 'px';
  box.style.top = positionY + 'px';
  if (positionX >= 200 || positionY >= 200) {
    clearInterval(intervalId);
    }
  }, 50);

What’s the difference between setInterval() and requestAnimationFrame()?

setInterval() executes a function at fixed intervals, regardless of the browser’s rendering cycle. requestAnimationFrame() synchronizes with the browser’s repaint cycle, leading to smoother and more efficient animations.

Can I create 3D animations with Canvas?

While the 2D context is primarily used, you can achieve some 3D effects using techniques like isometric projection or by working with the webgl context (though that is more complex).

How do I handle user input (like keyboard or mouse events) in a canvas game?

You can use JavaScript’s event listeners (e.g., addEventListener('keydown', ...) or addEventListener('click', ...) ) to capture user input and update your game state accordingly.


Written By:
Michael Karén

Free Resources