Home > Article > Web Front-end > Example analysis of the role of beginPath() and closePath() in canvas
This article brings you an example analysis of the functions of beginPath() and closePath() in canvas. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The function of beginPath is very simple, it is to start a new path, but it is very important in the process of using canvas drawing
Let’s look at a small piece of code first:
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 has no errors, but we get two yellow squares with a side length of 100px, instead of one green and one yellow. Why is this?
In fact, the drawing methods (fill, stoke) in canvas will draw all paths after the last "beginPath". In the above code, the first rectangle is filled twice, the first time Green, yellow for the second time, so we got two yellow rectangles. Similarly for drawing line segments, or other curves, graphics, no matter where you moveTo, as long as you don't have a beginningPath, you are drawing a path.
If the graphics you draw are inconsistent with what you imagined, remember to check beginPath
When talking about beginPath, you have to mention closePath. In fact, there is no relationship between the two. closePath means close. The path is not the end of the path. It just connects the end point of the path to the starting point, rather than starting a new path.
We add a closePath after the first fill in the above code, and we still get two yellow rectangles.
But if we add a beginPath later, we will get two rectangles of different colors.
In short, don't try to start a new path by closing a path, and if you don't close the path, even if you start a new path, it will not be closed.
The above is the detailed content of Example analysis of the role of beginPath() and closePath() in canvas. For more information, please follow other related articles on the PHP Chinese website!