xxxxxxxxxx
71
let points = [];
function setup() {
createCanvas(400, 400);
points = generatePoints(6, width/2);
}
function draw() {
background(50);
fill(255);
noStroke();
drawPoints(points, width/2, height/2)
}
function mouseReleased() {
points = generatePoints(6, width/2 - 10);
}
function drawPoints(points, x, y) {
beginShape();
for(let i = 0; i < points.length; i ++) {
const point = points[i];
vertex(x + point.x, y + point.y);
}
endShape(CLOSE);
}
function generatePoints(numSegments, radius) {
const segmentPoints = pointsForSegment(numSegments, radius);
return snowflakeFromSegment(numSegments, segmentPoints);
}
function pointsForSegment(numSegments, radius) {
const numPointsInSeg = int(random(4, 10));
const segmentPoints = [];
const segmentAngle = PI/numSegments;
// Generate random points in half the segment
for(let i = 0; i < numPointsInSeg; i ++) {
const a = random(segmentAngle);
const r = random(radius);
const x = cos(a) * r;
const y = sin(a) * r;
segmentPoints.push(createVector(x, y));
}
// Reflect those points on the y axis so that
// we have a full "branch" of the snowflake
for(let i = numPointsInSeg - 1; i >= 0; i --) {
const point = segmentPoints[i];
segmentPoints.push(createVector(point.x, -point.y));
}
return segmentPoints;
}
function snowflakeFromSegment(numSegments, segmentPoints) {
const points = [];
for(let i = 0; i < numSegments; i ++) {
const ang = i * TWO_PI/numSegments;
for(let j = 0; j < segmentPoints.length; j ++) {
const point = segmentPoints[j];
const a = atan2(point.y, point.x) + ang;
const r = point.mag();
points.push(createVector(cos(a) * r, sin(a) * r));
}
}
return points;
}