We use moveTo and lineTo methods to draw the line paths.
lineTo(x, y)
where x and y are the end points. Except this we also need to call stroke() or fill() method otherwise the lines will not be drawn on the canvas.
The following example will draw a horizontal line with the coordinates points (25,25) and (150,25).
var ctx; var canvas = document.getElementById("MyCanvas"); if (canvas.getContext) { ctx = canvas.getContext("2d"); ctx.moveTo(25, 25); ctx.lineTo(150, 25); ctx.stroke(); }
Line thickness
You can set the line thickness of line by set the lineWidth property of the canvas object. For example, suppose you want to to draw a line with thickness of 2 then you will use the following code:
ctx.lineWidth = 2;
Use multiple lineTo methods
The following snippet draws a multiple connected lines.
var ctx; var canvas = document.getElementById("MyCanvas"); if (canvas.getContext) { ctx = canvas.getContext("2d"); ctx.moveTo(25, 25); ctx.lineTo(150, 25); ctx.lineTo(190, 85); ctx.lineTo(300, 50); ctx.stroke(); }
Result will be: