HTML and CSS Reference
In-Depth Information
When you create a
canvas
element in HTML you will generally assign an
id
attribute so you can
access in JavaScript using the
getElementById()
method. You don't have to; you can access it using the
getElementsByTagName()
method or use the new query selectors that I described in Chapter
5
.
Once you have the canvas element, you'll then get its drawing context by calling
getContext()
. You must
specify which context to use. The context specifies a set of API functions and drawing capabilities. The only one
that is generally available is “2d” and we will be using that exclusively in this chapter. There is work being done to
define a “3d” context.
Drawing Rectangles
Unlike SVG, the only shape that you can draw directly is a rectangle. You can draw more complex shapes using
paths, which I'll explain later. There are three methods that you can use to draw rectangles:
•
clearRect()
- clears the specified rectangle
•
strokeRect()
- draws a border around the specified rectangle with no fill
fillRect()
- draws a filled-in rectangle
Each of these methods takes four parameters. The first two define the x and y coordinates of the top-left corner
of the rectangle. The last two parameters specify the width and height, respectively. The drawing context has the
strokeStyle
and
fillStyle
properties that control how the border or fill will be drawn. You set these before drawing
the rectangle. Once set, all subsequent shapes are drawn with these properties until you change the properties.
•
■
Tip
Just like svG, in canvas, the top-left corner of the canvas element has the x and y coordinates of 0, 0.
To demonstrate drawing rectangles, you'll start by drawing the chess board, which contains eight rows of
eight squares each.
eXerCISe 10-2. DraWING a SIMpLe CheSS BOarD
1.
Add a canvas to the
index.cshtml
page by inserting the following markup in the
blank
div
that was created by the project template:
<canvas id="board" width="600" height="600">
Not supported
</canvas>
2.
Then add a
script
element after the
div
but still inside the
body
element using the
code shown in Listing 10-1.
Listing 10-1.
Drawing a simple chess board
<script id="chess board" type="text/javascript">
// Get the canvas context
var chessCanvas = document.getElementById("board");
var chessContext = chessCanvas.getContext("2d");
drawBoard();
// Draw the chess board
function drawBoard() {