Canvas Composition

What You’ll Learn
Canvas is a single pixel surface, but you can build rich visuals by composing drawings in layers. Composition is mainly about drawing order, transparency, and blending.
This page covers the basics of composition and introduces globalCompositeOperation (the key to masking and blend modes).
⚡ Quick Reference
Draw last = on topCanvas paints over existing pixels
globalAlpha0 (transparent) → 1 (opaque)
globalCompositeOperationsource-over, multiply, screen, destination-out…
ctx.globalAlpha = 0.7;
ctx.globalCompositeOperation = 'source-over';👀 Live Preview — Blend Modes
Change the blend mode and alpha to see how shapes combine on a single canvas.
Tip: destination-out works like an eraser. It removes pixels from what you already drew.
Drawing Order (Layering)
Canvas draws in order. The circle appears on top because it is drawn after the rectangle.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw a blue rectangle first
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 80);
// Draw a red circle second (on top)
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(150, 100, 40, 0, 2 * Math.PI);
ctx.fill();Transparency with globalAlpha
Use globalAlpha to make drawings semi-transparent so layers can show through.
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Base layer
ctx.globalAlpha = 1;
ctx.fillStyle = '#2563eb';
ctx.fillRect(50, 50, 140, 100);
// Top layer (semi-transparent)
ctx.globalAlpha = 0.6;
ctx.fillStyle = '#f97316';
ctx.beginPath();
ctx.arc(160, 120, 55, 0, Math.PI * 2);
ctx.fill();
// Reset alpha for future drawings
ctx.globalAlpha = 1;💡 Best Practices
Do
- Use
ctx.save()/ctx.restore()to scope composition changes - Reset
globalAlphaandglobalCompositeOperationafter special effects - Draw in layers: background → shapes → text → highlights
- Use offscreen canvases for expensive compositing if needed
- Test blend modes across browsers when you rely on them
Don’t
- Forget that these properties persist (they affect later drawings)
- Stack many blend operations on large canvases without profiling
- Use destination-out without understanding it erases existing pixels
- Assume drawing order doesn’t matter (it always does)
- Ignore accessibility when canvas conveys important information
❓ Frequently Asked Questions
globalAlpha), and blending (globalCompositeOperation).destination-out).ctx.save()/ctx.restore() or reset them after a special effect.Draw Arcs Next
Learn how to draw circles and arcs with ctx.arc() and combine them into shapes.
4 people found this page helpful
