xxxxxxxxxx
86
/*
Inspired by Nadieh Bremer https://github.com/nbremer/artinpi
Shows digits of pi, where each digit is represented by one line. The length is constant, but the angle and color is determined by the value.
*/
const numOfDigits = 1000;
let points = [];
let prev;
let i = 1;
const colors = ['#FF0000', '#FF7E21', '#FBFF00', '#85FF2E', '#2BFFED', '#0AA5FF', '#365EFF', '#9421FF', '#FF26F8', '#FF0F47'];
function setup() {
createCanvas(windowWidth, windowHeight, SVG);
strokeWeight(1);
background(0);
prev = createVector(0, 0);
points.push({
digit: -1,
pos: createVector(0, 0),
});
frameRate(120);
for (let i = 2; i < numOfDigits + 2; i++) {
const digit = pi.charAt(i);
const curr = p5.Vector.fromAngle(radians(360 * digit / 10), 10);
curr.add(prev);
points.push({
pos: curr,
digit,
});
prev = curr;
}
const upperLeft = createVector(0, 0);
const lowerRight = createVector(0, 0);
for (const p of points) {
if (p.pos.x < upperLeft.x) upperLeft.x = p.pos.x;
if (p.pos.y < upperLeft.y) upperLeft.y = p.pos.y;
if (p.pos.x > lowerRight.x) lowerRight.x = p.pos.x;
if (p.pos.y > lowerRight.y) lowerRight.y = p.pos.y;
}
const translation = createVector(0.5 * width - (lowerRight.x + upperLeft.x) / 2, 0.5 * height - (lowerRight.y + upperLeft.y) / 2);
const resizeFactor = Math.max((lowerRight.x - upperLeft.x) / width, (lowerRight.y - upperLeft.y) / height);
const midpoint = createVector(width / 2, height / 2);
points = points.map(p => {
p.pos.add(translation);
p.pos.sub(midpoint);
p.pos.mult(0.85 / resizeFactor);
p.pos.add(midpoint);
return p;
});
noStroke();
fill(255);
textSize(13);
textFont('Helvetica');
textAlign(RIGHT, BOTTOM);
// text('Visualizing pi: Each angle corresponds to a digit of pi.', width-10, height-10);
}
function draw() {
// 60 fps * 15s = 900 frames
for (let j = 0; j < numOfDigits / 900; j++) {
const digit = points[i].digit;
const c = color(colors[digit]);
c.setAlpha(255);
stroke(c);
line(points[i - 1].pos.x, points[i - 1].pos.y, points[i].pos.x, points[i].pos.y);
if (i++ >= points.length - 1) {
print('saved svg');
save('mySVG.svg'); // give file name
noLoop();
return;
}
}
}