What exactly is a canvas path, and what is the use of ctx.closePath()?

寵の児 提交于 2019-11-27 18:22:58

What is a path?

It's a series of path commands (moveTo, lineTo, arcTo, etc.) that define the boundary of a vector shape. You can then fill and/or stroke the path as desired.

What is the Use of closePath()?

Demo: http://jsfiddle.net/YrQCG/5/

// Draw a red path using closePath() in the middle
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.moveTo(50,100);
ctx.lineTo(100,150);
ctx.lineTo(150,100);
ctx.closePath();
ctx.lineTo(50,50);
ctx.stroke();

// Slide the next path over by 150 pixels    
ctx.translate(150,0);

// Draw a blue path using the exact same commands, but without closePath
ctx.beginPath();
ctx.strokeStyle = 'blue';
ctx.moveTo(50,100);
ctx.lineTo(100,150);
ctx.lineTo(150,100);
//ctx.closePath();
ctx.lineTo(50,50);
ctx.stroke();

                                         

Using closePath() causes the point of the pen to move back to the start of the current subpath, drawing a line from the current point back to that starting point; the next command starts from this new point. It's useful if you want to draw a fully outlined shape without explicitly drawing the last line.

It is equivalent to calling lineTo() with the location of the first point of your current subpath, followed by moveTo() to that same point (to establish a new subpath).

  • Seen above, we draw a V symbol using the first moveTo and following two lineTo commands. When we call closePath on the red path it draws the horizontal bar across and causes the next line to start from the top left corner.

  • When we don't call closePath in the blue path the next lineTo command continues on from the last drawn point.

Note that closePath() is not necessary most of the time, unlike beginPath() which you must call each time you want to start drawing a new path. (If you don't, all the old path drawing commands are part of the next drawing.)

This is the basic representation of closed path:

ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(100,0);
ctx.lineTo(100,100);
ctx.lineTo(0,100);    
ctx.closePath(); // <--the image right side has this line
ctx.stroke();

The result of closePath() is that the start and the end point will be bounded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!