Technologies and Software Engineering

Canvas globalCompositeOperation Guide

Overview

The globalCompositeOperation property determines how new shapes and images (source) are drawn relative to existing canvas content (destination). It manages both alpha compositing and color blending to enable complex visual effects like masking, erasing, and lighting.

Key Insights

Technical Details

Core Compositing Modes

Compositing modes control the placement and visibility of pixels based on the overlap between source and destination.

ModeBehaviorCommon Use Case
source-overDraws source on top of destination (Default).Standard layering.
destination-overDraws source behind destination.Adding backgrounds retroactively.
source-inKeeps source only where it overlaps destination.Clipping images to shapes.
destination-inKeeps destination only where it overlaps source.Dynamic masking.
source-outKeeps source only where it does not overlap destination.Drawing in negative space.
destination-outRemoves destination where the source overlaps.Eraser or “scratch-off” effects.

Blend Modes (Color Mixing)

Unlike basic compositing, blend modes use mathematical formulas to mix the colors of overlapping pixels.

Implementation: Creating an Eraser

To turn a drawing tool into an eraser, switch the operation to destination-out.

// Enable eraser mode
ctx.globalCompositeOperation = "destination-out";

ctx.beginPath();
ctx.arc(150, 75, 30, 0, Math.PI * 2);
ctx.fill(); // This circle now clears existing pixels

// Reset to default behavior
ctx.globalCompositeOperation = "source-over";

Decision Logic: The Mental Model

When selecting a mode, evaluate the desired outcome of the overlap:

  1. Keep Source? Use source-* modes.
  2. Keep Destination? Use destination-* modes.
  3. Only the Intersection? Use -in suffixes.
  4. Everything except the Intersection? Use -out suffixes.
  5. Mix Colors? Use Blend Modes (multiply, screen, etc.).

Application Scenarios

Tags:

Search