Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

478 CHAPTER 12 Drawing with HTML5


The second shape is also a triangle and is drawn like the first triangle, but the stroke
method is called after the fill method is called. The stroke method creates the yellow outline.
The third shape is also a triangle, but this code doesn’t call the closePath method. In this
example, the fill method implicitly calculates the fill area, but because the closePath method
is not called, there is no line from the end to the start; therefore, no outline is rendered from
the end to the start.
The fourth shape is a plus sign. This demonstrates the use of the moveTo method to create
a line that doesn’t start where the previous line ended. The stroke method creates the lines,
but the fill method doesn’t render anything.

Drawing rectangles
You can add rectangles to your path by calling the rect method. Keep in mind that if all you
need to do is draw a rectangle, you can use the fillRect and the strokeRect methods, dis-
cussed earlier in this lesson.
The rect method is useful when you are defining a complex shape. Instead of adding many
lineTo calls to draw a rectangle, you just call the rect method. The following is an example of
creating a shape that consists of a triangle and rectangle.
function drawRect() {
var canvas = document.getElementById('myCanvas')
, ctx = canvas.getContext('2d');

ctx.fillStyle = 'green';
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 10;

ctx.beginPath();
ctx.moveTo(100, 300);
ctx.lineTo(150, 250);
ctx.lineTo(200, 300);
ctx.rect(100, 300, 100, 100);
ctx.fill();
ctx.stroke();
}

The rendered output is shown in Figure 12-11. Notice in the rendered output that the
triangle and the rectangle are outlined.
Free download pdf