The last article demonstrated a basic implementation of the canvas element where an image was moved across the screen. While it was a simple example, the same effect could just as easily been achieved by modifying the properties of a handful of standard HTML elements like an IMG or DIV. Here we will tap into some of the more advanced functions of the canvas element to demonstrate some of its real power.
jsplatformer2.html
The only change made to the HTML file is the addition of a few buttons. When clicked these button set the currentFunction variable (described later), changing which function is run during the render loop.
jsplatformer2.js
As before, a number of global variables have been defined in the JavaScript file. [code]
FPS The target frames per second
SECONDSBETWEENFRAMES The number of seconds between each frame (which is the inverse of the FPS value)
HALFIMAGEDIMENSION Half of the width / height of the image we are drawing, which is used to position the image in the center of the canvas
HALFCANVASWIDTH Half of the width of the canvas, used in conjunction with HALFIMAGEDIMENSION to center the image in the canvas
HALFCANVASHEIGHT Half of the height of the canvas, used in conjunction with HALFIMAGEDIMENSION to center the image in the canvas
currentFunction The function to be run during the render loop
currentTime The time in seconds that the application has been running
sineWave A value between 0 and 1, used to animate the image
image The image to be drawn to the canvas
canvas A reference to the canvas element
context2D A reference to the 2D context of the canvas element
And, just like before, the init function is set to run once the window is loaded (see the last article for a description of the init function). [code]