setup()
setup() runs once when the sketch starts. This function attaches the canvas to a specific HTML container, which is essential for embedding animated backgrounds into web pages. The c.parent() method is the key to integrating p5.js with existing HTML.
function setup() {
// Create canvas and attach it to the background container
const container = document.getElementById('p5-background');
const c = createCanvas(container.offsetWidth, container.offsetHeight);
c.parent('p5-background');
noStroke();
initBubbles();
}
Line-by-line explanation (5 lines)
🔧 Subcomponents:
const c = createCanvas(container.offsetWidth, container.offsetHeight);
Creates a canvas that matches the HTML container's dimensions so the background fills the space perfectly
initBubbles();
Populates the bubbles array with 60 random bubble objects ready to animate
const container = document.getElementById('p5-background');- Finds the HTML element with id 'p5-background' so we can measure its size and attach our canvas to it
const c = createCanvas(container.offsetWidth, container.offsetHeight);- Creates a p5.js canvas that is exactly as wide and tall as the container, so the background fills the entire space
c.parent('p5-background');- Tells p5.js to place the canvas inside the 'p5-background' div instead of at the bottom of the page
noStroke();- Removes outlines from all shapes so bubbles appear as clean, filled circles with no borders
initBubbles();- Calls the initBubbles function to create 60 bubble objects with random positions, sizes, and velocities