HTML5 Canvas : Ellipse
The previous article said that rectangle is the only native drawing method provided by HTML5 canvas, which is not entirely true, because Google browser provides the method of drawing ellipse.
Draw ellipse
Drawing method:
//Draw ellipse
//x: X axis coordinate of the center of the ellipse.
//y: Y coordinate of the center of the ellipse.
//radiusX: radius of the major axis of the ellipse.
//radiusY: radius of the minor axis of the ellipse.
//rotation: the angle of rotation of the ellipse in radians (non angular degrees).
//startAngle: the angle of the starting point to be drawn, measured from the X axis, in radians (non angle degrees).
//endAngle: the angle of the end point at which the ellipse will be drawn, in radians (non angle degrees).
//anticlockwise: optional. If it is true, draw the ellipse anticlockwise, and vice versa.
context.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
For example:
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
ctx.ellipse(100,100,80,50,0,0,Math.PI*2);
ctx.fillStyle="#058";
ctx.strokeStyle="#058";
ctx.fill();
ctx.stroke();
Extended ellipse method
We can directly extend the CanvasRenderingContext2D
object to make up for some browsers that do not implement elliptical support.
Using arcto
and arc
to achieve it is also relatively simple and does not need complex calculation. Because arcto
, arc
only provides the function of drawing positive arc. To draw elliptical arc, it can be realized with scale
deformation.
This method is recommended to implement the code:
if (CanvasRenderingContext2D.prototype.ellipse == undefined) {
CanvasRenderingContext2D.prototype.ellipse = function(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) {
this.save();
this.translate(x, y);
this.rotate(rotation);
this.scale(radiusX, radiusY);
this.arc(0, 0, 1, startAngle, endAngle, anticlockwise);
this.restore();
}
}
- Link : https://www.zdyla.com/en/post/html5-canvas-ellipse.html
- Copyright Notice : Unless otherwise stated, please contact the author for authorization and indicate the source!