Do I have to have the content.beginPath() and content.closePath()?

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 certain of. I commented out the two lines and the line still displayed. What is the significance of these two lines.

Question: What does the beginPath() and closePath() do?

Code:

context.lineJoin='round';
context.lineCap='butt';
context.beginPath();
context.moveTo(10, 100);
context.lineTo(35, 100);
context.lineTo(35,125);
context.stroke();
context.closePath();

Answers:

Answer

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:

two lines a triangle

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:

a double-red-blue stroked line and a blue line a red line and a blue line

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();
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.