How to draw paths?
Let's first draw one line
Here you go, the script that drew the brown line above.
The methods that really matters are "moveTo", "lineTo" ,"stroke" and "strokeStyle".
|moveTo(x,y)||move to starting point with coordinate x and y.|
|lineTo(x,y)||Draw a line to this point from starting point. Again x and y being the coordinate.|
|strokeStyle||CSS color of the line|
|beginPath||Before you start drawing a new line with different color, you will have to call "beginPath".|
Check out the demo below, "beginPath" method is playing an important role. Without it, the last "stroke" will redraw the previous line with the last-called "strokeStyle" color.
You may notice in the demo above, there are two buttons to help you draw a vertical line, however, one draws a one pixel line and the other draws a two pixels line. What makes the difference as follows:-
c4_context.moveTo(300, 10); c4_context.lineTo(300, 190);
c4_context.moveTo(300.5, 10);c4_context.lineTo(300.5, 190);
In order to draw a line with 1 pixel wide, you simply have to shift the coordinate to 0.5 pixel to the left or right (up or down). This is because integer value of the coordinate is to be considered at the edge of each pixel. Drawing a line at the edge will simply make the line spread across two adjacent pixels. By shifting the coordinate 0.5 pixel, the line will still spread between two pixels but occupy half of each pixel.