The ctx.closePath() method indicates that we would like a closed path: draw from the last point to the first.
Try this:
Source code:
var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
// Path made of three points (defines two lines)
ctx.moveTo(20,20);
ctx.lineTo(100, 100);
ctx.lineTo(100,0);
// Close the path, try commenting this line
ctx.closePath();
// indicate stroke color + draw first part of the path
ctx.strokeStyle = "blue";
ctx.stroke();
Lines 5-7 define a path made of two consecutive lines. If we just call stroke() after that, two lines will be drawn on the canvas.
Line 10 indicates that we would like a closed path. In this case, the call to stroke() at line 14 will draw the two lines plus an extra line that connects the last point of the path to the first one. It will draw a closed triangle!
Try commenting the line 10 in the online example and see the results