I am trying to draw lines in a circle like the spokes of a wheel. I am getting stuck because I do not know how to get the coordinates from the end point of the circle. It all works well as long as I draw lines from the rim to the centre of the circle but I am unable to make the lines stop on the inner circle, the hub of the wheel.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<body>
<script type="text/javascript">
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.arc(75, 75, 70, 0, 2 * Math.PI);
ctx.arc(75, 75, 20, 0, 2 * Math.PI);
var part = ( 2 * Math.PI ) / 8;
for( i=1; i<=8; i++ ) {
ctx.arc(75, 75, 70, 0, (part*i) );
ctx.lineTo( 75, 75 );
}
ctx.stroke();
</script>
</body>
</html>
The result of the above script:
Maybe the solution is simple, but I have only discovered the canvas object in javascript yesterday.
Is there a way to convert the position where the arc ends, to its x and y coordinates?
I know I can calculate these positions using math but I was hoping for an easier solution.
2
Answers
The solution involves a little bit of trigonometry and math.
Consider the following code. I replaced the numbers with variables with intuitive names.
Basically, you need to translate the endpoints of the line by a certain amount. This amount will depend on the radius, but changes with the rotation angle. This where
sin
andcos
come in.radius * sin(a)
andradius * cos(a)
will give the projection of the rotated distance on the x and y axisradius
is taken as the radius of inner and outer rims.oldX
andoldY
are just the centers of these rims.This gives the following result.
If you are looking for a solution without complex maths, you could just draw two circles. Then draw a spoke,
rotate()
1/8 turn, add another spoke, and repeat until all the spokes are in.