Prerequisite Reading
Please read
https://paulmontgomerycode.wordpress.com/2014/05/09/html5-canvas-introduction/
before continuing…
Overview
This course will demonstrate a very simple animated circle which bounces right and left across the canvas using HTML5 Canvas via CreateJS. I conceptually think of the HTML page as an application which happens to run in a web browser. This demo is completely self contained within the single HTML file (aside from the CreateJS CDN).
Code Repository
https://github.com/PaulMontgomery/html5_canvas_training
… for the full source of the working demo.
To view the demo, click here:
https://github.com/PaulMontgomery/html5_canvas_training/blob/master/canvas_training_1.html
Detailed Code Analysis
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5 Canvas Training Course 1</title>
This is just basic HTML, moving on.
<script src="http://code.createjs.com/createjs-2013.12.12.min.js"></script>
This is the CDN link for the CreateJS version that I am using. This is handy for development but you take a dependency on network accessibility to run the demo. In production systems, I would suggest downloading a local copy of CreateJS for reliability.
<script>
// Draws an animated bouncing circle on the canvas
// Paul Montgomery (paulmontgomery.code@gmail.com) 2014/05/09
// Descriptions and explanations are at:
// https://paulmontgomerycode.wordpress.com/2014/05/09/html5-canvas-training-course-1/
var stage, canvas_width, canvas_height, circle_shape, circle_radius = 50;
The script tag indicates that JavaScript follows. These are some global variables that are useful for the demo:
- stage – This is the “stage” on which all objects are placed
- canvas_width – This will later hold the width of the canvas as defined by the HTML at the end of the code
- canvas_height – … height of the canvas
- circle_shape – The CreateJS Shape object which holds the circle graphic that will be drawn later
- circle_radius – The radius of the circle; changing this will cause the circle to increase or decrease in size (50 pixel default)
function demo_preinit() {
console.log("demo_preinit() called");
demo_canvas = document.getElementById("demo_canvas");
canvas_width = demo_canvas.width;
canvas_height = demo_canvas.height;
console.log("demo_canvas is " + canvas_width + " by " +
canvas_height + " pixels in size");
demo_canvas.oncontextmenu = function(e) {
e.preventDefault();
}
stage = new createjs.Stage(demo_canvas);
demo_init();
}
This is a common pattern in all of my code to create a preinit() function which then calls an init() later. It is not apparent why this is important yet but it relates to loading of external media such as images or sound (which is not done in this demo). Later demos will explain this in more detail but it gives the media a chance to load fully before trying to use them (which would cause an error if they are not loaded yet). See CreateJS Preload for more details and examples.
Line 2 is just a common debug/diagnostic method that I use to show progress of an application. Browsers are all different but in Firefox you may right click the HTML screen and “Inspect Element” and then click the “Console” button to see these messages.
Line 3 will be in most any HTML5 Canvas code in that it associates the HTML canvas defined at the bottom of the HTML example with the CreateJS library in order to control the canvas directly. Just make sure that the name in the HTML is the same or an error will occur. This same method may be used to access almost any HTML/DOM entity that has a unique id.
Lines 4 and 5 show access to the canvas by obtaining the HTML defined canvas and finding out what the x and y dimensions of the object are.
Lines 8 to 10 prevent right clicks on the canvas from bringing up a web browser menu. It isn’t always necessary but this will be useful later in this course.
Line 12 associates the canvas with the stage where everything “acts”. Again, this or something similar will likely be in most any project.
function demo_init() {
console.log("demo_init() called");
var graphics = new createjs.Graphics();
graphics.beginFill("#BB00BB");
graphics.drawCircle(0, 0, circle_radius);
circle_shape = new createjs.Shape(graphics);
circle_shape.moving_right = true;
circle_shape.x = canvas_width / 2;
circle_shape.y = canvas_height / 2;
stage.addChild(circle_shape);
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener("tick", demo_tick);
console.log("Starting animated circle...");
}
This function begins the “real” work of the demo. By the end of this function, a circle will be drawn in the center of the canvas and everything will be set up to enable movement.
Lines 3-5 create a purple circle with radius of circle_radius (or 50 pixels by default). For this and all CreateJS functions, I would highly recommend reading the online CreateJS documentation to understand functionality and parameters. Please note that this will not actually do anything until we stage.addChild().
Line 6 creates a CreateJS Shape object which is what holds all graphics typically. This associates the circle graphics with the shape. This is very common to see in CreateJS code.
Line 7 is a simple Boolean method to indicate what direction the shape should move (to the right to start). More on this within the demo_tick() function.
Lines 8 and 9 simply move the shape to the center of the canvas using the x and y values previously stored.
Line 10 finally adds the shape to the stage. Any object that will be displayed or manipulated on the stage must be added to be part of the event chain.
Line 12 sets the canvas frames per second to 30.
Line 13 sets up events to be called 30 times (or whatever the FPS) a second and to call demo_tick() function each time.
function demo_tick() {
if (circle_shape.moving_right == true) {
circle_shape.x += 5;
if (circle_shape.x >= (canvas_width - circle_radius))
circle_shape.moving_right = false;
} else {
circle_shape.x -= 5;
if (circle_shape.x <= circle_radius)
circle_shape.moving_right = true;
}
stage.update();
}
Lines 2 and 6 basically funnel the workflow into a circle moving right or circle moving left branch of code. This is surely horribly inefficient and needlessly complex but I wanted to show how manual movement of objects may be accomplished. For a much easier way, please see CreateJS Tween documentation which is dedicated to moving objects around.
Lines 3 and 7 increment or decrement the shape location by 5 pixels each tick (remember, 30 ticks per second in the current configuration).
Lines 4, 5 and lines 8, 9 keep the shape from moving completely off of the canvas. At the point where it would leave the canvas, the shape changes direction and starts moving the other way.
Line 12 is the key to almost anything happening in this demo. The stage (and everything on the screen) won’t move or change in any way without a state update to redraw the screen. If you find a tick()-like function without stage.update(), something is likely wrong.
</script>
</head>
<body onload="demo_preinit();">
<h1>HTML5 Canvas Training Course 1</h1>
<canvas id="demo_canvas" width="500" height="300" style="background-color:#EEEEEE">
<p>Your browser does not support HTML5 Canvas which is required to see this content.</p>
</canvas>
</body>
</html>
Line 1 ends the JavaScript section.
Line 4 is super important for the demo operation. There are many ways to kick-off the JavaScript code but I chose to use the onload ability of the body tag to call demo_preinit(). Without this, the page would sit there statically doing nothing (no circle or anything).
Lines 6-8 is where the canvas is defined for the JavaScript to manipulate, it defines the canvas dimensions and color (I made the canvas slightly grey for visibility, usually the canvas is “invisible”) and the line 7 text will automatically show up on any web browser that does not support the HTML5 canvas feature. This is really nice so that a user doesn’t sit at a blank screen waiting for action; there is immediate notification.
That is pretty much it for the first demo; not too hard at all is it? The code could obviously be much smaller but this is a great template to use when creating other projects.
Please see the next course: HTML5 Canvas Training Course 2: Mouse Interactions
https://paulmontgomerycode.wordpress.com/2014/05/14/html5-canvas-training-course-2/