This guide will be the first in a series. Our primary tasks will include initializing a canvas using the 2D context, rendering a basic circle, and animating the circle. This will all run in the browser.
If, after reading this tutorial, you want to get deep into HTML5 Canvas animations, I recommend Core HTML5 Canvas: Graphics, Animation, and Game Development (Core Series).
If you'd like to skip the tutorial and download the complete, working files, they can be downloaded here.
We'll start by setting up the following folder structure, and populate them with empty files.
▾ root/ ▾ css/ styles.css ▾ js/ main.js ▾ vendor/ anim-loop.js stats.min.js ▾ lib/ ▾ renderers/ Renderer2D.js ▾ shapes/ Circle.js Shape.js core.js index.html
Make sure you download the vendor files from https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ and https://github.com/mrdoob/stats.js/.
styles.css with the following. All we're doing here is stripping all the margins and padding from the page, and styling the canvas so that it's visible. Feel free to change the canvas' border to any color you prefer.
Now that we have our canvas element onscreen, we're ready to initialize it with the properties required to render future shapes. The next batch of files will form the core rendering engine, and the code is distributed to keep the major functions separate and easy to manage.
Responsible for bringing all the top level components together and instantiating them. Also, responsible for providing a main API to the coder to make it easier for them to call functions within these top level components.
Manages the canvas, shapes, and rendering so the coder doesn't have to worry about low-level details.
Shape.js and Circle.js
Isolates the generic shape code and code to render a circle so that it's easier to manage. Each shape has it's own
render function where it will store it's logic for drawing itself to the canvas. This way, the coder doesn't have to call the Canvas API's
fill functions. They simply need to create the shape and
Renderer2D will simply call
render on every frame.
Because the core animation engine has been isolated into the
lib folder, we can think of it as a black box. As a code using this animation library, we no longer need to worry about what goes on in there. We only need to update the
main.js file to create and animate shapes.
If everything is working properly, we should be able to navigate to the
index.html file in the browser and watch our circle animate to the right side of the screen. To repeat the animation, simply refresh the page.
- Core HTML5 Canvas: Graphics, Animation, and Game Development (Core Series)
- HTML5 Canvas: Native Interactivity and Animation for the Web
- WebGL: Up and Running: Building 3D Graphics for the Web