DEV Community

Dennis Wueppelmann
Dennis Wueppelmann

Posted on

Set FPS and toggle your animation with requestAnimationFrame()

Did you know you can build your own animations and toggle them with JS?

In this article I want to share a little codepen that shows how you can control an animation. The object we will animate is a small drawing on the HTML Canvas. The tool to animate something manually is the requestAnimationFrame method. This function will execute a callback function every x times per second matching your monitors refresh rate. The method returns an ID which can be used to stop the animation:

const animationId = window.requestAnimationFrame(animate);
// ...
window.cancelAnimationFrame(animationId);
Enter fullscreen mode Exit fullscreen mode

One important thing to know is that you have to call the requestAnimationFrame Method inside of your callback function. But that's basically all the magic on how to build your own animation.
If you want to use a custom frame per second count for your animation there is a simple solution. You have to only call the requestAnimationFrame if enough time has passed since the last animation.

Enough theory here is the codepen where you can see it in action:

The animation draws lines on the canvas in a circle and will stop if the lines reach 3/4 of of the circle. In the settings the animation is set to a specific FPS count aswell.

Examples with 10, 30 and 60 FPS:

Alt Text

Alt Text

Alt Text

Please note there are multiple ways to measure the passed time for your FPS. E.g. you could use the performance api or you could use the passed timestamp of the requestAnimationFrame function. I just used a simple solution which is by far not the best.

Creative Coding Workbench

This article is part of my progress for the Digital Ocean Hackathon Project 'Creative Coding Workbench':

Used features:

  • draw sketch on HTML canvas
  • expose sketch settings to UI
  • export sketch for print
  • toggle sketch animation

Used Technologies:

  • Sapper
  • Digitial Ocean App Platform

I decided to end my project with this set of features. The next article will be my submission to the Hackathon. Stay tuned for this article as I will describe my full project and the future plans with this little tool.

Top comments (0)