https://editor.p5js.org/tinaaayu/sketches/DPLiw-vQ3
lanterns
: an array to hold all the lantern objects.numLanterns
: the total number of lanterns to be created (10 in this case)lanterns
array.function setup() {
createCanvas(400, 600); // creates a canvas of 400x600 pixels
// initialize lanterns
for (let i = 0; i < numLanterns; i++) {
let x = random(50, width - 100); // random x position for each lantern
let y = random(50, height - 100); // random y position for each lantern
let size = random(30, 60); // random size of the lanterns
let swaySpeed = random(1, 1.5); // random speed for swaying
let color = [random(180, 255), random(180, 255), random(180, 255)]; // random pastel colors
lanterns.push(new Lantern(x, y, size, swaySpeed, color)); // create lanterns and store in array
}
}
constructor:
x
, y
), size, sway speed, and color. it also tracks whether the lantern is lit (isLit
).class Lantern {
constructor(x, y, size, swaySpeed, lanternColor) {
this.x = x; // x position of the lantern
this.y = y; // y position of the lantern
this.size = size; // size of the lantern
this.swaySpeed = swaySpeed; // speed of swaying
this.angle = 0; // angle for swaying (used in sine wave)
this.lanternColor = lanternColor; // color of the lantern
this.isLit = false; // boolean to check if lantern is lit (clicked)
}
drawing the lantern:
drawLantern
method handles the visual rendering of the lantern. it uses rounded rectangles to create the soft shape of the lantern, and also adds a string on top . when the lantern is lit, a glow effect is shown and the lantern’s color becomes brighterdrawLantern() {
this.sway(); // apply swaying effect
if (this.isLit) {
this.glow(); // if the lantern is lit, show glow effect
fill(this.lanternColor[0], this.lanternColor[1], this.lanternColor[2], 260); // brighter color
} else {
fill(this.lanternColor[0], this.lanternColor[1], this.lanternColor[2], 150); // dimmer color
}
noStroke();
//string at the top of the lantern
stroke(150);
line(this.x, this.y - this.size * 1.2, this.x, this.y - this.size * 1.5);
noStroke();
// main lantern body
rect(this.x - this.size / 2, this.y - this.size / 2, this.size, this.size * 1.2, 20);
// Bottom attachment of the lantern
rect(this.x - this.size / 6, this.y + this.size / 2, this.size / 3, this.size / 5, 5);
}
glow effect:
glow
method draws a soft glowing ellipse around the lantern when it’s lit, using the lantern's color with some transparency to create the glowing effectglow() {
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); // glowing circle around the lantern
pop();
}