xxxxxxxxxx
90
let lanterns = [];
let numLanterns = 10;
function setup() {
createCanvas(400, 600);
// initialize lanterns
for (let i = 0; i < numLanterns; i++) {
let x = random(0, width -100);
let y = random(0, height-100);
let size = random(40, 60);
let swaySpeed = random(1, 1.5);
let color = [random(180, 255), random(180, 255), random(180, 255)];
lanterns.push(new Lantern(x, y, size, swaySpeed, color));
}
}
class Lantern {
constructor(x, y, size, swaySpeed, lanternColor) {
this.x = x;
this.y = y;
this.size = size;
this.swaySpeed = swaySpeed;
this.angle = 0;
this.lanternColor = lanternColor;
this.isLit = false;
}
drawLantern() {
this.sway();
// set color of the lantern, if lit, add a glow
if (this.isLit) {
this.glow();
fill(this.lanternColor[0], this.lanternColor[1], this.lanternColor[2], 260);
} else {
fill(this.lanternColor[0], this.lanternColor[1], this.lanternColor[2], 150);
}
noStroke();
// string above the lantern
stroke(150);
line(this.x, this.y - this.size * 1.2, this.x, this.y - this.size * 1.5);
noStroke();
// draw lantern
rect(this.x - this.size / 2, this.y - this.size / 2, this.size, this.size * 1.2, 20);
rect(this.x - this.size / 6, this.y + this.size / 2, this.size / 3, this.size / 5, 5);
}
// glow effect
glow() {
push();
noFill();
stroke(this.lanternColor[0], this.lanternColor[1], this.lanternColor[2], 100);
strokeWeight(10);
ellipse(this.x, this.y, this.size * 1.5, this.size * 2);
pop();
}
// sway motion
sway() {
this.angle += this.swaySpeed * 0.01;
this.x += sin(this.angle) * 0.5;
}
// is lantern clicked
checkClicked(mx, my) {
let d = dist(mx, my, this.x, this.y);
if (d < this.size) {
this.isLit = !this.isLit; // toggle lighting on/off
}
}
}
function draw() {
background(255, 230, 230);
for (let i = 0; i < lanterns.length; i++) {
lanterns[i].drawLantern();
}
}
function mousePressed() {
for (let i = 0; i < lanterns.length; i++) {
lanterns[i].checkClicked(mouseX, mouseY);
}
}