HTML and CSS Reference
In-Depth Information
// translate to centre to rotate properly
ballctx.translate(25, 25);
setInterval(draw, 10);
function draw() {
ctx.clearRect(0, 0, width, height);
ballctx.rotate(Math.PI/180*5); // 5 degrees
// draw at the 0,0 position
ballctx.drawImage(ballImg, 0, 0, ballImg.width,
¬ ballImg.height, -25, -25, 50, 50);
// copy the rotated source
ctx.drawImage(ballctx.canvas, x, y);
if (x + dx > width || x + dx < 0)
dx = -dx;
if (y + dy > height || y + dy < 0)
dy = -dy;
x += dx;
y += dy;
All the action is happening in the draw function, but only after
I've fi nished setting up. The setup dynamically creates the ball
canvas, hides it (because I don't need it to be seen on the
page—it's just a utility for the effect), and translates the canvas
so that the rotation happens in the centre of the canvas. You
might ask why do I put the ball canvas in the document if it
doesn't need to be seen? In the case of a canvas, if you don't
add it to the DOM, the size doesn't initialise properly. So when
you try to draw to the canvas, there's no height or width, which
causes errors when drawing. To circumvent that, I've set the
display style to none and then dropped it in to the DOM. Presto!
Now I can draw safely without errors.
The draw function then runs every 1/100th of a second (10 milli-
seconds), constantly incrementing the x and y position and
Search WWH ::

Custom Search