✨regular polygons
browser ⟩ canvas ⟩ path ⟩ example ⟩ regular polygons
👉 see: Canvas+ext

💾 replit:canvas polygon
const {floor} = Math;
// ⭐ import
import { vec, linearCombination } from './js/Vector.js';   // 👔 Vector
import { $ } from './js/Node+ext.js';            // 👔 Node+ext
import { } from './js/Canvas+ext.js';            // 👔 Canvas+ext
// --------------------------------------------------------------------
// draw on canvas
$('canvas').draw2D(ctx => {         // 👔 Node+ext, 👔 Canvas+ext
    
    const r  = 50;                  // radius
    const dx = 20;                  // padding between polygons
    const c0 = vec(2*r, 2*r);       // center of first polygon, 👔 Vector
    const v  = vec(2*r + dx, 0);    // vector for translation
    const u  = vec(0, 2*r + dx);    // ...
    ctx.lineWidth = 4;
    
    // polygons (subpaths)
    [3, 4, 5, 6, 7, 8].forEach((n,i) => {
        ctx.drawPolygon(n, {
            // c0 + a*u + b*v
            center: c0.plus(linearCombination([floor(i/3), i%3], [u,v])), 
            radius: r,
            fillStyle: `hsl(${60*i} 90% 50%)`,
        });
    });
});History
0: (-) archived// 2023.01.21 - 09:19 (-) archived
// --------------------------------------------
// 🔸 ctx.polygon(): regular polygon (subpath)
//
// parameters: parameters
// - n   : number of sides
// - x, y: center
// - r   : radius
//
// require: 
// - Vector, vec(), polar()
CanvasRenderingContext2D.prototype.polygon = function(n, x, y, r, {
    startAngle = -Math.PI/2,     // starting angle
    clockwise = true,            // clockwise by default
}={}) {
    const center = vec(x,y);     // center of polygon
    const delta = 2 * Math.PI / n * (clockwise ? 1 : -1);    // dθ = ± 2π / n
    
    // begin new subpath (at first vertex)
    this.moveTo(...center.add(polar(r, startAngle)).coords);
    // connect first (n-1) sides
    for (let i = 1; i < n; i++) {
        this.lineTo(...center.add(polar(r, startAngle + delta * i)).coords);
    }
    
    // connect back to first vertex
    this.closePath();
};Last updated
Was this helpful?