Introduction
Stained glass has been a beautiful art form for centuries, adorning churches, homes, and public buildings with vibrant colors and intricate patterns. In this tutorial, we'll explore how to simulate the appearance of stained glass using modern web technologies: HTML, CSS, and JavaScript.
The implementation uses the HTML Canvas API to generate Voronoi-like patterns that mimic the cellular structure of traditional stained glass, complete with the characteristic dark "lead lines" that separate the colored panes.
The Showcase
Below you'll find six different variations of the stained glass effect. Each variation demonstrates a different color palette and animation style. Use the toggle to turn animations on or off.
How It Works
The Voronoi Algorithm
The core of the stained glass effect uses a simplified Voronoi diagram algorithm. Each "cell" in the stained glass is defined by a seed point, and every pixel on the canvas is colored based on which seed point it is closest to.
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let minDist = Infinity;
let closestCell = null;
for (const cell of cells) {
const dist = Math.hypot(x - cell.x, y - cell.y);
if (dist < minDist) {
minDist = dist;
closestCell = cell;
}
}
// Color pixel based on closest cell
}
}
Animation
The animation is achieved by slowly moving the seed points over time. Each cell has a velocity vector that determines its movement, and cells bounce off the edges of the canvas to stay within bounds.
Color Palettes
Each variation uses a carefully curated color palette designed to evoke different moods:
- Classic: Traditional stained glass colors (red, blue, green, gold)
- Sunset: Warm oranges and pinks transitioning to purple
- Ocean: Cool blues and teals with purple accents
- Forest: Natural greens with golden highlights
- Cosmic: Deep purples and magentas for a space-like feel
- Traditional: Earthy browns and blues for an antique look
Mobile-Friendly Design
The showcase uses CSS Grid with auto-fit and minmax() to create a responsive layout that adapts to any screen size. On mobile devices, the panels stack vertically for easy viewing.
Implementation Tips
-
Performance: For better performance on mobile devices, consider reducing the cell count or disabling animation by default.
-
Accessibility: Provide a toggle for users who may be sensitive to motion or who prefer static displays.
-
Customization: The color palettes and cell counts can be easily customized by modifying the StainedGlass class options.
Conclusion
Creating stained glass effects with web technologies is a fun way to combine art and code. The techniques shown here can be adapted for various creative projects, from website backgrounds to interactive art installations.