how can I draw lines around a circle using HTMLcanvas? I am more interested on the math.
CodePudding user response:
You need to compute the point on the circle and then the point that lies outside of the circle. Then use beginPath
, moveTo
, lineTo
and finally stroke
to draw the line.
To compute a point at distance d
from a point of coords (x, y)
and angle an
you can use the following formula:
(x Math.cos(an) * d, y Math.sin(an) * d)
Now you compute 2 points, one using d
as the radius of the circle, and then d as something bigger than radius, depending on your needs.
I'm assuming that the an
is in radians, if it's measured in degrees then you can convert it like this:
const rad = an / 180 * Math.PI
CodePudding user response:
I've cobbled this quickly together:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//draw a circle
ctx.fillStyle = '#4A8';
ctx.beginPath();
ctx.arc(250, 250, 50, 0, 6.282);
ctx.fill();
//draw 12 lines
for(let i = 1; i <= 12; i ) {
let a = 360 / 12 * i
drawLine(a)
}
function drawLine(angle) {
/*
parametric form from wikipedia:
https://en.wikipedia.org/wiki/Circle#Equations
x,y are origin, r is radius a is angle
x = cx r * cos(a)
y = cy r * sin(a)
*/
ctx.beginPath();
ctx.lineWidth = 2;
//thanks Radu!
const rad = angle / 180 * Math.PI
//250 is the center of the circly both for x & y
//starting point on the circumfence of the circle
let x0 = 250 50 * Math.cos(rad)
let y0 = 250 50 * Math.sin(rad)
//endpoint of the stroke further outside with a length of 100
let x1 = 250 100 * Math.cos(rad)
let y1 = 250 100 * Math.sin(rad)
//draw from x0 to x1
ctx.moveTo(x0, y0);
ctx.lineTo(x1,y1);
ctx.strokeStyle = '#ff0000';
ctx.stroke();
}