Skip to content
Advertisement

Get coordinates of the points in an ellipse in HTML5 Canvas

In HTML5 Canvas, I know I can draw an ellipse with CanvasRenderingContext2D.ellipse(), but how can I draw some points on the ellipse path?

I can draw points on a circular path using the following codes:

const canvas = document.getElementById('thumbCanvas');
const ctx = canvas.getContext('2d');
const distance = 200;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
var angle = 0;
for(i = 0; i < 36; i++) {
  angleInRadian = angle * Math.PI / 180;
  ctx.fillRect(centerX - imgWidth / 2 + distance * Math.cos(angleInRadian), centerY - imgHeight / 2 + distance * Math.sin(angleInRadian), 5, 5);
  angle += 10;
}

Screenshot

p.s. ignore the colors and the dot at the center.

But how to do this with an ellipse? I don’t want to use ctx.scale() to distort the whole image.

Advertisement

Answer

At the moment your little rectangles are drawn along a perfect circle because the distance from the center is always the same. If you want to draw an oval, you have to vary the distance horizontally and vertically.

For example:

const canvas = document.getElementById('thumbCanvas');
const ctx = canvas.getContext('2d');
const distanceX = 60;
const distanceY = 30;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
let imgWidth = 10;
let imgHeight = 10;
var angle = 0;
for (i = 0; i < 36; i++) {
  angleInRadian = angle * Math.PI / 180;
  ctx.fillRect(centerX - imgWidth / 2 + distanceX * Math.cos(angleInRadian), centerY - imgHeight / 2 + distanceY * Math.sin(angleInRadian), 5, 5);
  angle += 10;
}
<canvas id="thumbCanvas"></canvas>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement