Drawing an ellipse with the Canvas' arc method

Like for drawing a circle, we use the arc method but the radius change depending on the direction.

Drawing an oval with Canvas HTML 5

The oval is figure with the shape of an egg. This includes the ellipse that is a circle in perspective is but is not necessarily an ellipse. The ellipse can be defined as a geometric figure with two axes of symmetry, while the circle is completely symmetrical. But according to Wolfram, the oval has no mathematical definition, in contrast to the ellipse (although all kinds of ovals correspond to a formula).
So, for simplicity, say that what we draw here is an oval with double symmetry or a circle flattened!

Drawing an oval is done with the scale method. This method modifies the proportions of an object after it is defined.

scale(x, y)

The arguments are the values of horizontal and vertical ratio. If we give such value to x as 0.5, the image will be reduced by 50% in the width direction.

If you want to create an oval that is twice as wide as high, we give the value 1 to x and to y the ratio of 0.5.


<canvas id="canvas3" width="400" height="200"></canvas>

function oval()
{
  var canvas = document.getElementById("canvas3"); 
  var context = canvas.getContext("2d");
  context.lineWidth="4";
  context.strokeStyle="green";
  context.scale(1, 0.5);
  context.beginPath();
  context.arc(200, 200, 180, 0, 2 * Math.PI);
  context.stroke();
}
oval(); 

We must point out one thing. Although the height is 100 pixel canvas, it gave the arc method a value of 100 for the argument y.
This is because the scale method are applied to the coordinates of the figure and not just its shape.
The ratio of 50% of the argument y of scale applies to the argument y of arc too.

Unfortunately the ratio also applies to the width of the line, so that the oval has not the even thickness elsewhere.

Full code for drawing a regular ellipse

To have a regular line, we must restore the original context before calling the stroke method so that the change in proportions do not apply to the thickness of the plot (though it applies to its shape).

The final code for drawing any oval shape:

<canvas id="canvas4" width="400" height="200"></canvas>

function drawOval(x, y, rw, rh)
{
  var canvas = document.getElementById("canvas4"); 
  var context = canvas.getContext("2d");
  context.save();
  context.scale(1,  rh/rw);
  context.beginPath();
  context.arc(x, y, rw, 0, 2 * Math.PI);
  context.restore();
  context.lineWidth=4;
  context.strokeStyle="orange";
  context.stroke();  
}

drawOval(200,200,180, 90); 

Parameters of the drawOval function are x and y, the center of the shape, and the horizontal and vertical radius.
The ratio method for the vertical scale is then the ratio between these two radii, rh / rw.

Documents and related