Torna ai risultati

Disegnare poligoni regolari

  (agg. )
// w=320 h=280
//var step=2;
function setup() {
    createCanvas(320, 280);
    setCodeFont();
/* }
function draw() { */
    background( 230 );
    polygon( 5, 160, 140, 100 );
}
function polygon( vertexCount, centerX, centerY, radius ) {

    // draw origin, axes and circle
    stroke(212);
    noFill();
    ellipse( 160,140, 200,200 );

    // calculate vertices
    var angles = [];
    var vertices = [];
    var angleStep = TWO_PI / vertexCount;
    for (var i=0; i<vertexCount; ++i) {
        angles.push(-HALF_PI + i*angleStep);
        var x = cos( angles[i] )*radius;
        var y = sin( angles[i] )*radius;
        vertices.push( createVector(x,y) );
    }

    // draw polygon
    stroke(0);
    fill(255);
    beginShape();
    for (var i=0; i<vertices.length; ++i) {
        vertex( centerX+vertices[i].x, centerY+vertices[i].y );
    }
    endShape( CLOSE );

    // segments
    stroke(192);
    line( 160,140, 160,42 );
    stroke(160);

    // points
    strokeWeight(5);
    stroke(0);
    point( centerX, centerY );

    strokeWeight(1);

    // texts
    noStroke();
    fill(0);
    text("centerX,centerY",160,155);
    text( "radius", 189,98 );
    // numbers
    for (var i=0; i<vertices.length; ++i) {
        var vert = vertices[i].copy();
        vert.mult(1.1);
        text( i+1, centerX + vert.x, centerY + vert.y );
    }
    noLoop();
}
// marks=6:4-6:30,9:9-9:56
function setup() {
    createCanvas(320, 280);
}

function draw() {
    background( 230 );
    polygon( 5, 160,140, 100 );  // pentagono / posizione: 160,140 / raggio: 100
}

function polygon( vertexCount, centerX,centerY, radius ) {
    let angleStep = TWO_PI / vertexCount;
    beginShape();
    for (let angle=-HALF_PI; angle<TWO_PI-HALF_PI; angle+=angleStep) {
        let x = centerX + cos(angle)*radius;
        let y = centerY + sin(angle)*radius;
        vertex( x, y );
    }
    endShape(CLOSE);
}

Per gestire e animare più poligoni si consiglia di importare e usare la libreria Shape5.js che permette di creare istanze di poligoni regolari con la possibilità di modificarne dinamicamente le proprietà.