HTML and CSS Reference
In-Depth Information
The code used for Figure 5.18 is relatively simple and breaks
down as follows:
1. Initialise the canvas and objects you want to draw.
2. Clear the canvas.
3. Draw the ball on the canvas.
To a d d e x t r a s p i c e , I r To t a t e B r u c e 's f a c e i in c i r c l e s w h i l s t h e b To u in c e s
around. So I'll have to do some rotation on the canvas, too.
FIguRE 5.18 While away the
hours whilst you watch Bruce's
face bounce around a canvas
Since I'm going to rotate Bruce's face, I'll let another canvas
handle that task (so I can keep my main canvas free from rota-
tion and translations). This keeps my tasks simple in that I'm
rotating an image of Bruce in one canvas while I'm working out
the position of his face and drawing in the second.
var ctx = document.querySelector('canvas').
¬ getContext(“2d”),
x = 100, // arbitrary start points
y = 50,
dx = 2,
dy = 4,
width = ctx.canvas.width,
height = ctx.canvas.height;
// load the image
ballImg = document.createElement('img');
ballImg.src = 'bruce-ball.png';
// once loaded, start the ball bouncing
ballImg.onload = function () {
var ball = document.createElement('canvas');
Search WWH ::

Custom Search