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:
JavaScript
x
12
12
1
const canvas = document.getElementById('thumbCanvas');
2
const ctx = canvas.getContext('2d');
3
const distance = 200;
4
const centerX = canvas.width / 2;
5
const centerY = canvas.height / 2;
6
var angle = 0;
7
for(i = 0; i < 36; i++) {
8
angleInRadian = angle * Math.PI / 180;
9
ctx.fillRect(centerX - imgWidth / 2 + distance * Math.cos(angleInRadian), centerY - imgHeight / 2 + distance * Math.sin(angleInRadian), 5, 5);
10
angle += 10;
11
}
12
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:
JavaScript
1
14
14
1
const canvas = document.getElementById('thumbCanvas');
2
const ctx = canvas.getContext('2d');
3
const distanceX = 60;
4
const distanceY = 30;
5
const centerX = canvas.width / 2;
6
const centerY = canvas.height / 2;
7
let imgWidth = 10;
8
let imgHeight = 10;
9
var angle = 0;
10
for (i = 0; i < 36; i++) {
11
angleInRadian = angle * Math.PI / 180;
12
ctx.fillRect(centerX - imgWidth / 2 + distanceX * Math.cos(angleInRadian), centerY - imgHeight / 2 + distanceY * Math.sin(angleInRadian), 5, 5);
13
angle += 10;
14
}
JavaScript
1
1
1
<canvas id="thumbCanvas"></canvas>