Beginpath's role is simple, which is to start a new path, but it's very important to use the canvas drawing process.
Let's look at a small piece of code:
var ctx=document.getelementbyid ("Canvas"). GetContext ("2d"); Ctx.beginpath (); Ctx.rect (150,150,100,100); Ctx.fillstyle= "green"; Ctx.fill (); Ctx.rect (0,0,100,100); Ctx.fillstyle= "Yellow"; Ctx.fill ();
Our code is not wrong, but it is two side length 100px Yellow square, instead of a green one yellow, this is why?
In fact, the drawing method (Fill,stoke) in the canvas, all the paths after "Beginpath" are drawn, in the code above the first rectangle is fill two times, the first green, the second yellow, so get two yellow rectangles, the same for the picture line segment , or other curves, graphs, no matter where you moveto, as long as you have no beiginpath, you are drawing a path.
If the graphic you are drawing is inconsistent with your imagination, check out the Beginpath.
Talking about Beginpath will have to mention the Closepath, in fact, there is no relationship between the two, closepath means to close the path, not the end of the path, it just connects the end of the path with the starting point, not to start a new path.
We add a closepath after the first fill in the code above, and still get two yellow rectangles.
But when we add a beginpath to the back, we get two rectangles of different colors.
In summary, do not attempt to start a new path by closing a path, and if you do not close the path, it will not close even if you start a new path.
On the importance of Beginpath () and Closepath () in canvas in HTML5