I am trying to build a near-perfect circle with quadratic curves in canvas. I have this function for setting up points around a circle and connecting them with quadratic curves:
function calcPointsCircle(cx, cy, radius, dashLength) {
var n = radius / dashLength,
alpha = Math.PI * 2 / n,
i = -1;
while (i < n) {
var theta = alpha * i,
theta2 = alpha * (i + 1);
points.push({
x : (Math.cos(theta) * radius) + cx,
y : (Math.sin(theta) * radius) + cy,
ex : (Math.cos(theta2) * radius) + cx,
ey : (Math.sin(theta2) * radius) + cy,
py : (Math.sin(theta) * radius) + cy
});
i+=2;
}
}
for (i = 0; i < points.length; i++) {
var p = points[i];
ctx.strokeStyle = '#fff';
ctx.quadraticCurveTo(p.x, p.py, p.x, p.y);
ctx.stroke();
}
It works, but the lines are currently straight (which is obvious, since I am using the points x and y coordinates for the control point):
I am looking for a way to automatically calculate the poisitions for the control points based on the circle radius and the number of points... All help is more then welcome
Here's how to calculate the controls points of a set of quadratic curves which approximate a circle circumscribing a regular polygon.
Given:
A centerpoint, radius & sidecount.
For each side of the polygon, calculate:
3 points on a circumscribing circumference and then calculate the quadratic curve control point that causes the curve to pass through those 3 points:
The 2 points of the polygon side are 2 of the 3 points
Calculate the sweep angle between the 2 points of a side (var sweep)
Bisect the sweep angle (sweep/2)
Use trigonometry to calculate the point on the circumference midway between the 2 points of the side.
Calculate the middle control point:
Example code and a Demo: