xxxxxxxxxx
135
//|================================|
//| CHAOS TRIANGLE |
//|--------------------------------|
//| JAMES MENDEL |
//| jamesmendel.github.io |
//| created: 02.Apr.2022 |
//|================================|
/*jshint esversion: 8 */
let BG_COLOR = 40;
let FG_COLOR = 200;
let PADDING;
let c1, c2, c3;
let corners;
let numPoints = 0;
let lastPoint;
function setup() {
frameRate(30);
createCanvas(600, 600);
background(BG_COLOR);
PADDING = 0.15*width;
c1 = new p5.Vector(PADDING, height-PADDING); // bottom left
c2 = new p5.Vector(width-PADDING, height-PADDING); // bottom right
c3 = new p5.Vector(width/2, PADDING); // top
corners = [c1, c2, c3];
push();
fill(FG_COLOR);
stroke(FG_COLOR);
strokeWeight(8);
point(c1.x, c1.y)
point(c2.x, c2.y);
point(c3.x, c3.y);
pop();
}
function draw() {
push();
fill(FG_COLOR);
stroke(FG_COLOR);
strokeWeight(5);
pt = makePoint();
lastPoint = pt;
point(pt.x, pt.y);
drawHistogram();
drawPointCount();
pop();
}
function makePoint() {
let pt, corner;
if(numPoints == 0) {
pt = makePointInsideTriangle();
}
else {
corner = corners[floor(random(0,3))];
x = (lastPoint.x + corner.x)/2;
y = (lastPoint.y + corner.y)/2;
pt = new p5.Vector(x, y);
}
numPoints++;
return pt;
}
function makePointInsideTriangle() {
let pt = new p5.Vector();
inside = false;
// randomly create point until lies within triangle
while(!inside) {
x = random(0, width);
y = random(0, height);
pt.set(x, y);
d1 = sign(pt, c1, c2);
d2 = sign(pt, c2, c3);
d3 = sign(pt, c3, c1);
has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0);
inside = !(has_neg && has_pos);
}
return pt;
}
// https://stackoverflow.com/a/2049593
function sign(p1, p2, p3) {
return ((p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y));
}
function drawHistogram() {
push();
stroke(FG_COLOR, 5);
strokeWeight(3);
line(pt.x, height-PADDING+15, pt.x, height-PADDING+20);
line(PADDING-15, pt.y, PADDING-20, pt.y);
pop();
}
function drawPointCount(){
push();
fill(BG_COLOR);
stroke(BG_COLOR);
rect(0, height, width, height-PADDING/2);
fill(80);
textStyle(BOLD);
textSize(16);
textAlign(CENTER, TOP);
x = width/2;
y = height-PADDING/2;
text(numPoints, x, y);
textSize(10);
text(lastPoint.x.toFixed(0) + " / " + lastPoint.y.toFixed(0), x, y+20);
pop();
}
function sleep(millisecondsDuration) {
return new Promise((resolve) => {
setTimeout(resolve, millisecondsDuration);
})
}