Languages
[Edit]
EN

JavaScript - canvas animations

0 points
Created by:
DEX7RA
580

In this article, we would like to show you how to make canvas animations using JavaScript.

1. Basic concept

Edit

Once the shape is drawn it stays that way. In order to move it, we need to redraw the shape and everything that was drawn before,

To draw a frame you need to:

  1. clear the canvas,
  2. save the canvas state,
  3. draw animated shapes,
  4. restore canvas state.

2. Practical example using requestAnimationFrame()

Edit

In this example, we create an animation using requestAnimationFrame() method.

With these approaches, the frames are being drawn at the most appropriate moment for the browser.

Simple example

Edit

This example doesn't contain any logic controlling the speed of the animation.

Complex example

Edit

Using lastTimestamp and currentTimestamp we are able to calculate how much time has passed since the last frame was drawn, so we can draw a smooth animation.

3. Inefficient solution using setInterval()

Edit

In this example, we present an alternative solution that clears the canvas and draws the square with a changed position (moved by 1px) every millisecond.

 

References

Edit
  1. Basic animations - Web APIs | MDN
  2. Window.requestAnimationFrame() - Web APIs | MDN
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join