HTML and CSS Reference
var myImage = new Image();
myImage.src = "Images/sample.jpg";
context.drawImage(myImage, 0,0, 50, 100);
The first parameter of the drawImage() method specifies the image that will be drawn. This can be an Image
object, as I've shown here. Alternatively, you can also specify an img , video , or canvas element that is already on
the page. The next two parameters specify the x and y location of the top-left corner of the image. The fourth and
fifth parameters are optional and specify the width and height, respectively, that the image will be scaled to fit
into. If you don't specify these parameters the image will be drawn using its intrinsic size.
The drawImage() method also allows you to supply four additional parameters. These are used to specify
only the portion of the image that should be displayed on the canvas. These additional parameters include an x
and y coordinate and a width and height to define the specified portion. Use the last four parameters if you only
want a portion of the image to be drawn. If these are omitted, the entire image will be included.
In this application you will be drawing 32 pieces using 12 different images. Also, later in this chapter you will
be adding code to move the pieces around. To facilitate this, you'll add some structure to your application. You
will define a class that will store attributes about a chess piece such as the image to use and its location on the
board. Then you'll implement a generic drawing function that uses the details from these attributes.
eXerCISe 10-3. DraWING CheSS pIeCeS
In the solution Explorer, right-click the Chapter 10 project and select the Add ➤ new
Folder links. Enter Images for the folder name.
The images for the chess pieces are included in the source code download file. You'll
find these in the Chapter 10 \Images folder. Drag all 12 files to the Images folder in
the solution Explorer.
Add the variable declarations shown in bold in Listing 10-2 to your script element.
This will define a variable to reference an Image object for each of the twelve image
files. It will also define an array that you will be using to store the chess pieces.
Listing 10-2. Defining the image variables
// Get the canvas context
var chessCanvas = document.getElementById("board");
var chessContext = chessCanvas.getContext("2d");
// Define the chess piece images
var imgPawn = new Image();
var imgRook = new Image();
var imgKnight = new Image();
var imgBishop = new Image();
var imgQueen = new Image();
var imgKing = new Image();
var imgPawnW = new Image();
var imgRookW = new Image();
var imgKnightW = new Image();
var imgBishopW = new Image();
var imgQueenW = new Image();
var imgKingW = new Image();