Skip to content

Instantly share code, notes, and snippets.

@RichardJohnn
Last active April 16, 2020 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardJohnn/c49dd037b034ddb419b412d8cc541f4d to your computer and use it in GitHub Desktop.
Save RichardJohnn/c49dd037b034ddb419b412d8cc541f4d to your computer and use it in GitHub Desktop.
Chaos Game
//chaos game (https://en.wikipedia.org/wiki/Chaos_game)
//parameters: n = 5, r = 2 & cannot pick same vertex twice
//demo: https://editor.p5js.org/RichardJohnn/sketches/VxFo5o_Yv
//image: https://i.imgur.com/iBFEZDO.png
let w ;
let h ;
let x = 0;
let y = 0;
let anchors = [];
let n = 5;
let r = 2;
let step = 700;
let sliceAngle = 0;
let current;
let currentI = 0;
let colour = "#ffffff";
function mid(first, second, r) {
return [
floor((first[0] + second[0]) / r),
floor((first[1] + second[1]) / r)
]
}
function polar2rectangular(theta, radius) {
return [
radius * cos(theta) + (w/2),
radius * sin(theta) + (h/2)
];
}
function setup() {
w = displayWidth;
h = displayHeight;
createCanvas(w, h);
background("#000");
stroke("#444"); //grey
angleMode(DEGREES);
blendMode(SCREEN); //so multiple grey points in the same position become lighter
sliceAngle = floor(360 / n);
current = [floor(random(w)), floor(random(h))];
//place 'anchors' (corners, verticies) on a circle
for (let theta = 0; theta < 360; theta += sliceAngle) {
let anchor = polar2rectangular(theta - 90, h / 2);
anchors.push(anchor);
}
strokeWeight(1);
}
function getIndex() {
let i = floor(random(anchors.length));
//not allowing the same vertex to be chosen twice can yield very different results!
if (currentI != i)
return i
else
return getIndex();
}
function draw() {
for (let x = 0; x < step; x += 1) { //add more dots per render to speed things up
let i = getIndex();
currentI = i;
current = mid(current, anchors[i], r);
point(current[0], current[1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment