โจregular polygons
Last updated
Last updated
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%)`,
});
});
});
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();
};