HTML and CSS Reference
In-Depth Information
The
moveTo(x,y)
function doesn't actually draw anything on the canvas but will move the cursor to another loca-
tion. Think of it as lifting your pencil off a piece of paper and moving it to another spot on the paper. The
x
and
y
parameters specify the coordinates for the new starting point.
The
lineTo(x,y)
function is similar to
moveTo()
, but this one draws on the canvas. The
x
and
y
parameters
specify the coordinates for the endpoint of the line. The start point is the last point that was added to the path.
If your path has more than one point and you want the path to form a closed shape, you need to call the
closePath()
function when you are done adding your points. This will attempt to close the path by drawing a
straight line between the last point you specified and the start of the path.
Once you have your path created, you can use the
fill()
function to fill in the area that the path outlines or the
stroke()
function to paint a line along the parts of the path that were drawn using the
lineTo()
function.
It is important to note that, unlike when drawing rectangles, your path will not be displayed on the canvas until you
call either
fill()
or
stroke()
. This “draw first, render later” process is key to the way that the Canvas API
works.
To set the color of the line, you can use the
strokeStyle
property:
ctx.strokeStyle = “rgba(255,255,255,0.4)";
The line width can be set using the
lineWidth
property:
ctx.lineWidth = 1.0;
Now that you understand how to create paths and draw lines, you can add the line to your canvas using the following
steps.
The code in this exercise can be found in folder 6.
1.
Open the
adscript.js
file in your text editor.
2.
First you need to create some variables that will make it easier to calculate the positions for your path.
Create a variable called
lineLength
and initialize it with the value
360
.
function drawAdvert() {
...
// Add the separator line
var lineLength = 360;
}