Clips and masks
Any node, a group included, can be cut down to part of itself, children and all:
clip: a rectangle. Only what is inside it is drawn. Scrolling lists, a window onto a bigger scene, a bar that fills up.mask: another node. The node is drawn only where the mask node is opaque. A portrait in a circle, a star that fills with colour, a text cut out of a picture.
Both work the same on WebGL2, WebGL1 and Canvas 2D, and give the same pixels, soft edges included.
const list = stage.add(engine.group({ x: 100, y: 120, clip: { x: 0, y: 0, width: 400, height: 300 } }))for (let i = 0; i < 20; i++) list.add(engine.text(`Level ${i + 1}`, { x: 20, y: 30 + i * 60, align: 'left' }))
engine.onFrame((dt) => { for (const row of list.children) row.y -= 40 * dt // move the children, not the clip})clip: { x, y, width, height } is a rectangle in the node’s own units: it moves, scales and rotates with the node.
Set it when making the node, or later (node.clip = { … }); null removes it. Clips inside clips intersect.
A clip is nearly free while no rotation is above it (on the node itself or on a group it is in). The renderer then cuts what it draws to the rectangle, on whole pixels, without breaking its batch of draw calls. Use clips freely.
A rotated clip is drawn as a mask of its rectangle, with a mask’s cost (below).
await engine.load({ photo: 'art/photo.webp' })const photo = stage.add(engine.sprite('photo', { x: 640, y: 360, anchor: 0.5 }))photo.mask = engine.shape({ type: 'circle', r: 80, fill: '#fff' })mask: node shows the node only where the mask node is opaque, times the mask’s alpha: half-transparent parts of
the mask show the node half-transparent. Any node can be a mask: a shape, a sprite, a text, a group.
- The mask is placed as a child of the masked node would be:
x,yare in the masked node’s units (here the circle is centred on the photo’s anchor), and it moves with the node. - Don’t add the mask to the stage. It is drawn only as the mask, never on its own. Animate it like any node
(
photo.mask.scale = 1.2, a tween). - Hidden (
visible = false), the mask is ignored and the node drawn whole.node.mask = nullremoves it. - A mask can have a clip or a mask of its own.
- A node with filters is filtered first, then drawn inside the clip and under the mask.
Hit tests
Section titled “Hit tests”Clips and masks only change what is drawn. engine.touched and engine.hits test
the node’s whole rectangle (or hitRadius), as if there were no clip or mask: a hidden part of a node still counts.
Skip what the children cannot see yourself, for example rows of a list outside its clip.