Draw slices in the Canvas and draw slices in the canvas
In HTML5 Canvas, we can usearc
Method 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.PI
That'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 inarc
The 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 ismoveTo
AndclosePath
, 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