
¿Cómo puedo dibujar líneas alrededor de un círculo usando HTMLcanvas? Estoy más interesado en las matemáticas.
Debe calcular el punto en el círculo y luego el punto que se encuentra fuera del círculo. Luego use beginPath , moveTo , lineTo y finalmente stroke para dibujar la línea.
Para calcular un punto a la distancia d de un punto de coordenadas (x, y) y ángulo an puedes usar la siguiente fórmula:
(x + Math.cos(an) * d, y + Math.sin(an) * d) Ahora calcula 2 puntos, uno usando d como el radio del círculo y luego d como algo más grande que el radio, según sus necesidades.
Supongo que el an está en radianes, si se mide en grados, entonces puedes convertirlo así:
const rad = an / 180 * Math.PI
He improvisado esto rápidamente juntos:
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(); }https://jsfiddle.net/rokt0v51/
Resultado: