JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
const _C = document.getElementById('canvas') /* canvas element */ ,
C = _C.getContext('2d') /* 2L canvas context */ ,
L = _C.width /* edge length of canvas square */ ,
O = -.5 * L /* top left corner coord if 0,0 is in the middle */ ,
R = L / Math.SQRT2 /* half diagonal of canvas square */ ,
RC = .05 * L /* polygon circumradius */ ,
UA = 2 * Math.PI / 360 /* unit angle = 1 degree */ ,
POLY = [] /* array to fill with polygons */ ,
N = 500 /* total number of polygons */ ,
/* hex values for paint buckets */
THEME = ['#c76cd8', '#ee4198', '#c9244e', '#e57442', '#f9c240'],
NT = THEME.length /* number of paint buckets */ ,
OPTS = ['fill', 'stroke'],
NO = OPTS.length,
FN = ['line', 'move'];
function rand(max = 1, min = 0, dec = 0) {
return +(min + (max - min) * Math.random()).toFixed(dec)
};
class RandPoly {
constructor() {
/* SHAPE PROPERTIES */
this.n = rand(8, 3); /* number of vertices */
this.α = 2 * Math.PI / this.n; /* base angle corresp to an edge */
/* PAINT PROPERTIES */
this.o = rand();
this.b = rand(NT - 1); /* number of paint bucket we put it in */
/* POSITION PROPERTIES */
/* polar coordinates */
this.r = rand(R + RC); /* position radius */
this.β = Math.random() * 2 * Math.PI; /* position angle */
this.γ = rand(1.5, .125, 3) * UA; /* revolution speed */
}
get coords() {
let vx = [],
f;
if (--this.r < 0) this.r = R + RC;
this.β += rand(1.1, .9, 3) * this.γ;
f = this.r / R;
for (let i = 0; i < this.n; i++) {
let ca = this.β + i * this.α;
vx.push([
Math.round(this.r * Math.cos(this.β) + f * RC * Math.cos(ca)),
Math.round(this.r * Math.sin(this.β) + f * RC * Math.sin(ca))
])
}
return vx
}
};
function draw() {
C.clearRect(O, O, L, L);
for (let i = 0; i < NT; i++) {
let b = POLY.filter(c => c.b === i);
for (let j = 0; j < NO; j++) {
let opt = b.filter(c => c.o === j);
C[`${OPTS[j]}Style`] = THEME[i];
C.beginPath();
opt.forEach(p => {
let vx = p.coords;
for (let k = 0; k <= p.n; k++) {
C[k ? 'lineTo' : 'moveTo'](...vx[k % p.n])
}
});
C.closePath();
C[`${OPTS[j]}`]();
}
}
requestAnimationFrame(draw);
};
function init() {
C.translate(-O, -O);
C.lineWidth = 3;
C.globalCompositeOperation = 'screen'
for (let i = 0; i < N; i++) {
let p = new RandPoly();
POLY.push(p);
}
draw()
};
init();