Sometimes, it might be useful to draw just one line.
It's interesting to see how we can write a single "draw line" function that takes the start and end coordinates, the color, the line width, etc., and give the impression of being done in "immediate" mode.
Here is the code for this "utility" function that you may find useful:
function drawLine(x1, y1, x2, y2, color, width) {
ctx.save();
// set color and lineWidth; if these parameters
// are not defined, do nothing (default values)
if(color)
ctx.strokeStyle = color;
if(width)
ctx.lineWidth = width;
// start a new path
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
ctx.restore();
}
Notice the save/restore of the context at the beginning/end of the function. This is REALLY a best practice to avoid affecting other functions' context.
Line 13 starts a new path so that the function will only draw what it is meant to draw: a single line.
Lines 15-17 move the "pen" at (x1, y1) then draw a line to (x2, y2), and the stroke at line 17 makes it appear on the screen.
Here is an example:
Source code extract:
drawLine(0, 0, 100, 100);
drawLine(0, 50, 150, 200, 'red');
drawLine(10, 100, 100, 10, 'green', 10);