On the importance of Beginpath () and Closepath () in canvas in HTML5

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.