Draw slices in the Canvas and draw slices in the canvas

Source: Internet
Author: User

Draw slices in the Canvas and draw slices in the canvas

In HTML5 Canvas, we can usearcMethod to draw a circle:

    // context.arc(x, y, r, sAngle, eAngle, counterclockwise);    var canvas = document.getElementById('canvas');    var ctx = canvas.getContext('2d');    ctx.arc(100, 100, 50, 0, 2 * Math.PI);    ctx.fill();

 

But how to create a sector? Is it easy to modify the end angle?2 * Math.PIThat's all?

    var canvas = document.getElementById('canvas');    var ctx = canvas.getContext('2d');    ctx.arc(100, 100, 50, 0, 1.5 * Math.PI);    ctx.fill();

However, we will see a chart that does not meet our expectation:

Because inarcThe method is used to create an arc. If the starting and ending points of the Arc are directly closed and then filled, the above figure is naturally drawn.

Knowing the cause is easy to solve. As long as this arc is closed with the center of the circle, it just forms a sector:

Var canvas = document. getElementById ('canvas '); var ctx = canvas. getContext ('2d '); // start a new path ctx. beginPath (); // shift to the center of the circle to facilitate the painting of ctx. translate (100,100); // move to the center ctx. moveTo (0, 0); // draw an arc ctx. arc (0, 0, 50, 0, Math. PI * 1.5); // closed path ctx. closePath (); ctx. fill ();

 

 

The focus here ismoveToAndclosePath, Set the starting point of the path to the center of the circle, and finally close the path, just become a sector.

Code can also be extracted as a common method, as follows:

    CanvasRenderingContext2D.prototype.sector = function(x, y, radius, sAngle, eAngle, counterclockwise) {    this.beginPath();    this.translate(x, y);    this.moveTo(0, 0);    this.arc(0, 0, radius, sAngle, eAngle, counterclockwise);    this.closePath();    return this;    };

 

 

From the technical blog of lanfei

 

Related Article

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.