xxxxxxxxxx
77
let stars = [];
let color1;
let color2;
let gradient;
function setup() {
createCanvas(400, 400);
changeColors();
drawGradient(0, 0, width, height, color1, color2);
createStars(100);
}
function draw() {
background(0);
drawGradient(0, 0, width, height, color1, color2);
drawStardust();
}
function changeColors() {
color1 = color(random(255), random(255), random(255));
color2 = color(random(255), random(255), random(255));
}
function mousePressed() {
changeColors();
drawGradient(0, 0, width, height, color1, color2);
}
function drawGradient(x, y, width, height, c1, c2) {
for (let i = y; i <= y + height; i++) {
gradient = map(i, y, y + height, 0, 1);
let c = lerpColor(c1, c2, gradient);
stroke(c);
line(x, i, x + width, i);
}
}
function createStars(num) {
for (let i = 0; i < num; i++) {
stars.push(new Star());
}
}
function drawStardust() {
for (let i = 0; i < stars.length; i++) {
stars[i].update();
stars[i].show();
}
}
class Star {
constructor() {
this.x = random(width);
this.y = random(height);
this.size = random(1, 3);
}
update() {
this.x += random(-0.5, 0.5);
this.y += random(-0.5, 0.5);
// Wrap around the canvas
if (this.x < 0) this.x = width;
if (this.x > width) this.x = 0;
if (this.y < 0) this.y = height;
if (this.y > height) this.y = 0;
}
show() {
fill(255);
noStroke();
ellipse(this.x, this.y, this.size, this.size);
}
}