In this section we will learn some of the basics of using the canvas API. Now that we have a context, we can call its methods to draw lines and shapes. The API has a whole host of methods that let you draw everything from the most basic lines, to shapes, and even bitmap images.
You can find the source code for this section in chapter4/canvas-examples/canvas-examples.html
.
The background of the canvas is transparent. Whatever background color you specify for the canvas element in your CSS will show through. You can clear the canvas, or a portion of it, using the context's clearRect()
method. It takes x, y, width, and height parameters and clears that part of the canvas.
context.clearRect(0, 0, canvas.width, canvas.height);
By default, when you draw on the canvas, lines are one pixel wide and the color is black. You can change these by setting global properties on the context
object.
penWidth
: This property sets the width that lines will be drawn with. It can be any decimal number. For example, you can have a line that is 1.5 pixels wide.strokeStyle
: This property sets the color that will be used to draw lines. It can be any one of the CSS color specifiers. For example, to draw in red you could use red
or #FF0000
, rgb(255, 0, 0)
, or rgba(255, 0, 0, 1)
.fillStyle
: This property sets the color that will be used to fill shapes. Like strokeStyle
it can be any CSS color specifier.globalAlpha
: This property sets the alpha or transparency amount to draw with. It can be any number from 0 to 1, where 0 is completely transparent and 1 is completely opaque.lineCap
: This property determines how the ends of lines are drawn. It can be one of the following:butt
draws a flat endround
draws a rounded endsquare
draws a square end
square
looks similar to butt
except that it has an extra rectangle drawn at the end, making it longer.
lineJoin
: This property determines how corners are drawn where two lines meet. It can be one of the following:bevel
draws a beveled or flat cornerround
draws a rounded cornermiter
draws a sharp corner3.141.202.54