HTML and CSS Reference
In-Depth Information
The magic behind this approach is provided by an alternative use of the drawImage() method of the Canvas
object. So far, when you've used drawImage() , you just specified three parameters: the image object itself, and the
coordinates in the X- and Y-axis. However, this method also accepts two additional uses:
One method allows you to scale up or down the image by specifying the target width and
height, like this:
drawImage(imageObject,
sourceX,
sourceY,
newWidth,
newHeight);
The final method allows you to draw a portion of the image object by specifying
drawImage(imageObject,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
destinationX,
destinationY,
destinationWidth,
destinationHeight);
Therefore, this will allow you to do the following, as shown in Listing 8-28.
Listing 8-28. Applying the drawImage() Method of the Canvas Object
// Before changing the values of ballPositionX and ballPositionY:
// Redraw the previous portion of the background that
// was overdraw by the ball
ctx.drawImage(backgroundTexture,
ballPositionX - ballRadius,
ballPositionY - ballRadius,
(ballRadius * 2),
(ballRadius * 2),
ballPositionX - ballRadius,
ballPositionY - ballRadius,
(ballRadius * 2),
(ballRadius * 2));
// Add the velocity to the position in the X and Y axis
ballPositionX += ballVelocityX;
ballPositionY += ballVelocityY;
// Paint the ball
paintBall(ctx, ballRadius, ballPositionX, ballPositionY);
But what if you wanted to somehow display an animation in your background? One possible way to approach this
task would be to use the technique described in the next section of this chapter.
 
Search WWH ::




Custom Search