xxxxxxxxxx
123
let oscillators = [];
let colors, rainbow;
let current = 0;
let listening = false;
let d = 24;
function setup() {
createCanvas(700,700);
background(51);
colors = [
color(255, 0, 0),
color(0, 255, 0),
color(0, 0, 255),
color(0),
color(255),
color(128),
color(0, 255, 255),
color(255, 0, 255),
color(255, 255, 0),
color(102, 68, 34),
color(255, 128, 0),
color(255, 128, 128),
color(128, 0, 128)
];
rainbow = [
colors[0], // Red
colors[10], // Orange
colors[8], // Yellow
colors[1], // Green
colors[6], // Blue
colors[2], // Indigo
colors[12] // Violet
]
// for (let i = 0; i < rainbow.length; i++) {
// const r = (i+1) * 37;
// const osc = new Oscillator(r, r, 18);
// osc.col = rainbow[i];
// oscillators.push(osc);
// }
}
function keyPressed() {
if (key === "l") {
console.log("Listening...");
listening = true;
}
}
function mousePressed() {
const r = dist(mouseX, mouseY, width/2, height/2);
const osc = new Oscillator(r, r, 18);
osc.angle = atan2(mouseY - height/2, mouseX - width/2);
osc.col = rainbow[current];
oscillators.push(osc);
current = (current+1) % rainbow.length;
}
function draw() {
background(51, 10);
push();
translate(width/2, height/2);
for (const osc of oscillators) {
osc.render();
osc.update();
}
pop();
noStroke();
fill(51, 128);
rect(0, height/2, width, height/2);
if (listening) {
let saving = true;
for (const osc of oscillators) {
if (osc.getPos().y >= 0) {
saving = false;
}
}
if (saving) {
d--;
}
if (d <= 0) {
console.log("Aligned!");
saveCanvas("rainbow", "png");
listening = false;
d = 32;
}
}
push();
stroke(colors[6]);
fill(255);
textAlign(CENTER, CENTER);
textSize(32);
text("Make raindrops by clicking on the canvas!", width/2, 7*height/8);
text("Press ' l ' to save the rainbow image!", width/2, 15*height/16);
pop();
}
class Oscillator {
constructor(r, period, size) {
this.r = r;
this.size = size;
this.period = period;
this.angle = 0;
this.col = random(colors);
}
getPos() {
return createVector(this.r * cos(this.angle), this.r * sin(this.angle));
}
update() {
this.angle += TWO_PI / this.period;
}
render() {
const x = this.r * cos(this.angle);
const y = this.r * sin(this.angle);
noStroke();
fill(this.col);
circle(x, y, this.size*2);
}
}