I need to work on canvas animations in Angular recently. And I found many tutorials but in plain JavaScript. Honestly, most examples are not so easy to follow. That's why I write up this post in the purpose of advertising TypeScript or ES6.
Please check out this GitHub repo for Canvas Animations Demos or visit the demo site, which includes 5 commonly seen animations (solar system, clock, bouncing ball, constellation, interactive text). This repo is purely written in TypeScript and has no third party dependencies.
A good place to start learning Canvas Animations is MDN Canvas API, which contains two informative sections on basic animations and advanced animations.
The principle of animation is simple: redraw the canvas in every time frame. Thus, we need a function, eg. draw()
, to draw on the canvas and need a mechanism to execute that function over a period of time. In draw()
method, you can define shapes, colors, and/or physics for objects on canvas. In order to generate animations, draw()
method also needs to compute changes of objects. Then in order to re-render canvas, we call draw()
method over a set period of time. There are 3 ways to schedule updates: window.setInterval()
, window.setTimeout()
, and window.requestAnimationFrame()
. In my demos, I use window.requestAnimationFrame()
to control animations.
Therefore, the skeleton of a typical canvas animation class is as follows.
In CanvasAnimation
class, we save canvas
and context
(canvas rendering context) for internal usage. Then we can start animation as needed by calling window.requestAnimationFrame()
method with a callback. Notice that, the call back function ()=> this.draw()
is using fat Arrow Function syntax. ()=> this.draw()
is needed to preserve the this
context of the current CanvasAnimation
instance.
Execution is called by new CanvasAnimation(canvas)
in Lines 16β17. Here you need to cast canvas to be <HTMLCanvasElement>
to get proper type and intellisense. Very simple, isn't it?
The first 3 animation demos in this GitHub repo are rewritten from MDN examples. They basically follow the same pattern described in the above code snippet. I hope you would agree that with Types and Objects, the code is much readable and understandable.
For the sake of completeness, I have included 2 more animation demos, which are examples of configurable animation and interactive animation.
One tricky question in the interactive animation demo is how to correctly get mouse cursor position relative to canvas. We should remember to take care of screen scroll effect. Below is an example.
Hope this article adds some value to the topic of using TypeScript to make Canvas Animations. Again, source code is in this GitHub repo and you can also visit this demo site. Feel free to leave comments below. Thank you.
πΊ πΊ Cheers! π» π»
βοΈ Subscribe to CodeBurst's once-weekly Email Blast, π¦ Follow CodeBurst on Twitter, view πΊοΈ The 2018 Web Developer Roadmap, and πΈοΈ Learn Full Stack Web Development.