PROGRAMMA PER DISEGNARE UN POLIGONO REGOLARE DI num LATI
Tratto da
PROGRAMMA INTERATTIVO CHE DISEGNA UN POLIGONO REGOLARE CON I NOMI DEI VERTICI
<html> <body>
<canvas id="lavagna" width="450" height="450"> Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById('lavagna');
c.width=c.width;
var ctx=c.getContext("2d");
var Ox = c.width/2;
var Oy = c.height/2;
ctx.translate(Ox,Oy);
const num = 5 //se si vuole un pentagono
const u = 200 //unità di misura preferita
const alfa = 2*Math.PI/num; //angolo giro diviso il numero di lati
const p = (3*Math.PI - alfa)/2; //270° - alfa/2 in radianti: in questo modo avrete il poligono in posizione standard
//variate p per ruotare
//esempio
// p = Math.PI/4
x[0] = Math.cos(p); //vedi TEORIA
y[0] = -Math.sin(p);
for (i=1; i<=num-1; i+=1){
x[i]=x[i-1]*Math.cos(-alfa) - y[i-1]*Math.sin(-alfa);
y[i]=x[i-1]*Math.sin(-alfa) + y[i-1]*Math.cos(-alfa);
}
ctx.beginPath();
ctx.moveTo(u*x[0],u*y[0]);
for (i=1;i<=num-1;i+=1){
ctx.lineTo(u*x[i],u*y[i])
}
ctx.closePath()
ctx.stroke();
ctx.beginPath();
ctx.textAlign='center'; //allineamento orizzontale
ctx.textBaseline="middle";//allineamento verticale
ctx.font = "normal 12px monospace"; //tipo carattere
for (i=0; i<=num-1; i+=1){
ctx.fillText(String.fromCharCode(cod1),(u+6)*x[i],(u+6)*y[i])
cod1+=1;
}
</script>
</body>
</html>