Skip to content

Clip Paths

A clip path turns a shape into a clipping mask — instead of being filled or stroked, the shape defines a visible region. Any sibling elements rendered after the clip shape (within the same group) are only visible where they overlap with the clip region.

Usage

Set clip: true on any shape to use it as a clip path:

ts
import {
    createCircle,
    createGroup,
    createRect,
} from '@ripl/core';

const group = createGroup({
    children: [
        // Clip shape — defines the visible region
        createCircle({ clip: true,
            cx: 150,
            cy: 100,
            radius: 80 }),

        // Clipped content — only visible inside the circle
        createRect({ fillStyle: '#3a86ff',
            x: 0,
            y: 0,
            width: 300,
            height: 200 }),
    ],
});

The rect fills the entire area, but only the portion inside the circle is visible.

How It Works

When a shape has clip: true:

  1. The shape's path geometry is built as normal
  2. Instead of calling fill() or stroke(), the context's clip() method is called
  3. The clip region remains active for all subsequent siblings in the same group
  4. When the group finishes rendering, the clip is automatically removed (via save/restore scoping)

This means clips are scoped to their group — they don't leak to elements outside the group.

Properties

The clip option is available on all Shape types:

OptionTypeDefaultDescription
clipbooleanfalseWhen true, the shape acts as a clip path instead of rendering visually

When clip is true, the autoFill, autoStroke, fillStyle, and strokeStyle properties have no effect — the shape is never drawn, only used as a clipping mask.

Combining with Transforms

Clip shapes support all the same transforms as regular shapes — translateX, translateY, rotation, transformScaleX, transformScaleY, etc. The clip region will be transformed accordingly.

ts
createCircle({
    clip: true,
    cx: 150,
    cy: 100,
    radius: 80,
    transformScaleX: 1.5, // Elliptical clip
});

Works with Both Contexts

Clip paths work identically with both the Canvas and SVG contexts:

  • Canvas: Uses the native CanvasRenderingContext2D.clip() method
  • SVG: Creates a <clipPath> element in <defs> and applies clip-path="url(#...)" to subsequent sibling elements

Demo

The demo below shows a circle clip path masking a gradient-filled rectangle and a pattern of lines. Only the portions inside the circle are visible.