HTML and CSS Reference
In-Depth Information
ball.height = 50;
ball.width = 50;
ballctx = ball.getContext('2d');
// 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
finished setting up. In the setup, the code dynamically creates a
new canvas for the ball but doesn't put it inside the DOM. This
canvas is then translated so the rotation of Bruce's face happens
in the centre of the canvas. I can still use the 2D context of this
“unattached” canvas and I explicitly give this canvas a height and
width (otherwise it's automatically set to 300x150px).
The draw function then runs every 1/100th of a second (10 mil-
liseconds), constantly incrementing the x and y position and
redrawing the ball canvas on the main canvas, but not before
the blanket clearing of the canvas with ctx.clearRect(0, 0,
width, height) , which is effectively resetting the entire effect.
So that's it. Animation. Probably most akin to a flip-book animation.
Search WWH ::

Custom Search