Does the beginPath and the closePath have to be included for this line to draw or for all of the graphics. I have the new HTML 5 Canvas book but this I was not completely ce
No, beginPath
and closePath
are not necessary.
A canvas context has a current path. You can add instructions to that path with methods such as moveTo
and lineTo
, among others. When you're done constructing the path, you can use methods such as stroke
and fill
, which draw on the canvas using the current path.
closePath
is just another instruction you can add. You may not notice its effect when using fill
, but when using stroke
, it will (essentially) do a line back to the starting position, ‘closing’ the path. Compare and contrast:
ctx.moveTo(10, 10); ctx.moveTo(10, 10);
ctx.lineTo(90, 10); ctx.lineTo(90, 10);
ctx.lineTo(90, 90); ctx.lineTo(90, 90);
ctx.closePath();
ctx.stroke(); ctx.stroke();
beginPath
, on the other hand, discards the previous path and lets you start a new one. Without it, you'd be appending more and more to the previous path, which may be undesirable. Compare and contrast:
ctx.moveTo(10, 10); ctx.moveTo(10, 10);
ctx.lineTo(90, 10); ctx.lineTo(90, 10);
ctx.lineWidth = 4; ctx.lineWidth = 4;
ctx.strokeStyle = "red"; ctx.strokeStyle = "red";
ctx.stroke(); ctx.stroke();
ctx.beginPath();
ctx.moveTo(10, 20); ctx.moveTo(10, 20);
ctx.lineTo(90, 20); ctx.lineTo(90, 20);
ctx.lineWidth = 2; ctx.lineWidth = 2;
ctx.strokeStyle = "blue"; ctx.strokeStyle = "blue";
ctx.stroke(); ctx.stroke();
beginPath()
clears the old path so you can define a new one.
closePath()
connects the first point with the last point and is not needed in your example. In any case it would have be used before stroking of filling to have an effect on the rasterized result.