Home > Web Front-end > H5 Tutorial > body text

Example analysis of the role of beginPath() and closePath() in canvas

不言
Release: 2018-09-15 15:55:48
Original
2704 people have browsed it

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template