HTML and CSS Reference
In-Depth Information
Using Gradients
You can also use a gradient to fill a shape instead of a solid color. To do that you must first create a gradient object
using the drawing context's createLinearGradient() method. This method takes four parameters, which are the
x and y coordinates of the beginning and ending points of the gradient. This allows you to specify if the gradient
should go from top-to-bottom, left-to-right, or corner-to-corner. The gradient is computed across the entire
canvas. You cannot define gradients for individual elements.
You must then define the color stops. Each color stop defines a position along the gradient and a color. At a
minimum, you'll need a color stop at 0 and 1, which define the beginning and ending colors. You can also add
color stops in between these if you want to control the transition. For example, if you want to define the color at
the halfway point, use 0.5.
Finally, you'll use this gradient to specify the fillStyle property. To try it out, add the following code shown
in bold:
function drawBoard() {
chessContext.clearRect(0, 0, 600, 600);
var gradient = chessContext.createLinearGradient(0, 600, 600, 0);
gradient.addColorStop(0.0, "#D50005");
gradient.addColorStop(0.5, "#E27883");
gradient.addColorStop(1.0, "#FFDDDD");
chessContext.fillStyle = gradient ;
chessContext.strokeStyle = "red";
Save your changes and press F5 to start the application. The page should now look like Figure 10-3 . Notice
that the color transitions across the canvas, not across each square.
Figure 10-3. The board using a gradient fill
Using Images
Now you're ready to add the chess pieces, which will be drawn using image files. It is really easy to add an image
to a canvas. You create an Image object, set its src property, and then call the drawing context's drawImage()
method like this:
 
Search WWH ::




Custom Search