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

前端 未结 2 1257
南笙
南笙 2021-01-04 00:31

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

相关标签:
2条回答
  • 2021-01-04 01:03

    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();
    
    0 讨论(0)
  • 2021-01-04 01:16

    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.

    0 讨论(0)
提交回复
热议问题