In this article, we will delve into the use of the HTML5 Canvas API. We will learn how to draw multiple spheres in random positions, a fundamental technique for creating dynamic backgrounds, particles in video games, or even pieces of generative art.
If you are new to this world, I recommend reading our guide on the Basic Use of Canvas to become familiar with the initial concepts.
Initial Canvas Setup
The first step is to obtain a reference to the element in the DOM and define its 2D drawing context. It is good practice to ensure that the Canvas dimensions are dynamic.
const myCanvas = document.getElementById("myCanvas");
const ctx = myCanvas.getContext("2d");
// We get current dimensions
const width = myCanvas.width;
const height = myCanvas.height;Logic for Random Drawing
To draw points or spheres randomly without them going outside the edges, we must consider the figure's radius in our boundary calculations (maxWidth and maxHeight).
const radius = 10;
const n = 50; // Number of spheres
for (let i = 0; i < n; i++) {
// We calculate positions avoiding the edges
const centerX = Math.random() * (width - radius * 2) + radius;
const centerY = Math.random() * (height - radius * 2) + radius;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.fillStyle = "#e74c3c"; // Elegant color (coral red)
ctx.fill();
ctx.strokeStyle = "#c0392b"; // Slightly darker border
ctx.lineWidth = 2;
ctx.stroke();
ctx.closePath();
}- ctx.beginPath(): Fundamental for starting a new path and preventing all figures from connecting to each other.
- Math.random(): Generates a value between 0 and 1, which we scale to the dimensions of our canvas.
- ctx.arc(): The standard method for creating perfect arcs and circles.
Making the example interactive
We can take this exercise further by allowing the user to control the quantity, size, and color of the spheres using HTML5 inputs.
// Capturing values from the interface
const userRadius = document.getElementById("radio").value;
const count = document.getElementById("n").value;
const color = document.getElementById("color").value;
// Tip: To clear the canvas before redrawing
ctx.clearRect(0, 0, width, height);You can see the result of this interactive experiment at the following links:
Beyond static points: Animation and Generative Art
Drawing random points is the first step toward creating particle systems. If we wrap our drawing logic within a requestAnimationFrame function, we could make these spheres move, bounce, or change size in real time.
The Canvas is an incredibly powerful tool. Once you master basic drawing, the next logical step is to explore more advanced techniques such as image processing or even media capture. For example, you can learn how to activate the camera with JavaScript and project the video directly onto a Canvas to apply filters in real time.