setup()
setup() runs once when the sketch starts. Here we initialize the canvas, create the off-screen buffers that power the tilt-shift effect, generate the city, and position the camera. The dual-buffer approach is key: one buffer holds the sharp 3D render, the other holds a blurred version, and draw() composites them together.
function setup() {
createCanvas(windowWidth, windowHeight);
pixelDensity(1); // keep consistent across devices
// Off-screen WEBGL buffer for the 3D scene
cityBuffer = createGraphics(width, height, WEBGL);
cityBuffer.pixelDensity(1);
// Smaller buffer for cheap blur (downscale then upscale)
const blurScale = 4;
blurBuffer = createGraphics(
Math.max(1, Math.floor(width / blurScale)),
Math.max(1, Math.floor(height / blurScale))
);
initCity();
initCamera();
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-window canvas that will display the final composited image
cityBuffer = createGraphics(width, height, WEBGL);
Creates an off-screen 3D rendering target where the city scene is drawn
blurBuffer = createGraphics(
Math.max(1, Math.floor(width / blurScale)),
Math.max(1, Math.floor(height / blurScale))
);
Creates a downscaled 2D buffer used to create the blur effect via pixelation
createCanvas(windowWidth, windowHeight);- Creates the main canvas at full window size where the final tilt-shift image will be displayed
pixelDensity(1);- Sets pixel density to 1 to keep rendering consistent across devices (prevents extra upscaling on high-DPI screens)
cityBuffer = createGraphics(width, height, WEBGL);- Creates a WEBGL off-screen buffer at full resolution—this is where the 3D city gets rendered before effects are applied
const blurScale = 4;- Defines a downscaling factor—4 means the blur buffer is 1/4 the resolution of the main canvas
blurBuffer = createGraphics( Math.max(1, Math.floor(width / blurScale)), Math.max(1, Math.floor(height / blurScale)) );- Creates a small 2D buffer that will store the downscaled (blurry) version of the city for compositing
initCity();- Calls the function that generates all buildings and lays out the city grid
initCamera();- Calls the function that positions the camera at the starting viewpoint