Animations

Animate boxes between layouts

Twelve boxes switch between scatter, shelf, grid and ring. One Animate.shape.morphAll call moves and resizes all of them, with a staggered start.

// Demonstrates Animate.shape.morphAll on free-standing shapes: twelve boxes
// of different sizes switch between four layouts. Each box moves and changes
// its size at the same time; stagger starts them one after another.

import {
    VisQuill, Reactive, Boxes, Segments, Points, Animate, EasingFunctions, Svg,
    type Box, type RvgAnimation,
} from "@visquill/visquill-gdk"
import './styles.css'

// ─── Layout ───────────────────────────────────────────────────────────────
const stageTop     = 110
const stageBottom  = 30
const designWidth  = 760     // the layouts are drawn for this stage size
const designHeight = 480     // and scaled down on smaller frames
const gap          = 12
const buttonWidth  = 100
const buttonHeight = 26
const buttonGap    = 8
const buttonTop    = 60
const duration     = 700
const stagger      = 50

// ─── Boxes ────────────────────────────────────────────────────────────────
// Width and height of each box at scale 1.
const sizes: [number, number][] = [
    [80, 60], [50, 50], [100, 40], [40, 90], [70, 70], [60, 30],
    [90, 80], [30, 60], [60, 100], [110, 50], [50, 40], [40, 40],
]

// Fixed offsets of the box centres for the scatter layout.
const scatter: [number, number][] = [
    [-250, -120], [-60, -150], [150, -130], [290, -60], [-170, 10], [30, -30],
    [200, 60], [-300, 110], [-80, 120], [110, 160], [320, 140], [-10, 40],
]

const layouts = ["Scatter", "Shelf", "Grid", "Ring"]

export function run(div: HTMLDivElement) {
    const rvg    = VisQuill.create(div, "demos-box-layouts-")
    const canvas = rvg.canvas

    // ─── Instruction label ────────────────────────────────────────────
    const instructions = canvas.text.label("Pick a layout · the boxes move one after another", "instructions")
    Reactive.do([rvg.frame], () => {
        Points.moveDown(Segments.midPoint(Boxes.topSide(rvg.frame)), 25, instructions)
    })

    // ─── Stage and boxes ──────────────────────────────────────────────
    const stage = canvas.shapes.box()
    Reactive.do([rvg.frame], () => {
        const width  = Boxes.width(rvg.frame).value
        const height = Boxes.height(rvg.frame).value - stageTop - stageBottom
        Boxes.box(Points.moveDown(Boxes.topLeft(rvg.frame), stageTop), width, height, stage)
    })

    const boxes = sizes.map((_, i) => canvas.visuals.box(`box tone-${i % 3}`))

    // ─── Targets: one box per layout and box, plus the start order ────
    // Each layout returns the target boxes in the order the boxes should start.
    const targetsFor = (layout: number): { order: number[], targets: Box[] } => {
        const center = Boxes.center(stage)
        const scale  = Math.min(1, Boxes.width(stage).value / designWidth, Boxes.height(stage).value / designHeight)
        const boxAt  = (cx: number, cy: number, w: number, h: number) =>
            Boxes.centeredBox(Points.move(center, cx * scale, cy * scale), w * scale, h * scale)
        const boxAround = (c: { x: number, y: number }, w: number, h: number) =>
            Boxes.centeredBox(c, w * scale, h * scale)

        if (layout === 0) {
            // Scatter: fixed centres, own sizes.
            const order = sizes.map((_, i) => i)
            return { order, targets: order.map(i => boxAt(...scatter[i], ...sizes[i])) }
        }
        if (layout === 1) {
            // Shelf: tallest first, two rows standing on their shelf.
            const order   = sizes.map((_, i) => i).sort((a, b) => sizes[b][1] - sizes[a][1])
            const rows    = [order.slice(0, 6), order.slice(6)]
            const targets: Box[] = []
            rows.forEach((row, r) => {
                const rowWidth = row.reduce((sum, i) => sum + sizes[i][0], 0) + (row.length - 1) * gap
                const shelfY   = r === 0 ? -20 : 150
                let x = -rowWidth / 2
                row.forEach(i => {
                    const [w, h] = sizes[i]
                    targets.push(boxAt(x + w / 2, shelfY - h / 2, w, h))
                    x += w + gap
                })
            })
            return { order, targets }
        }
        if (layout === 2) {
            // Grid: 4 × 3 equal squares, row by row.
            const cell  = 80
            const order = sizes.map((_, i) => i)
            return {
                order,
                targets: order.map((_, k) => {
                    const col = k % 4, row = Math.floor(k / 4)
                    return boxAt((col - 1.5) * (cell + gap), (row - 1) * (cell + gap), cell, cell)
                }),
            }
        }
        // Ring: centres on a circle, clockwise from the top, own sizes.
        const radius = 190
        const order  = sizes.map((_, i) => i)
        return {
            order,
            targets: order.map((i, k) => {
                const angle = k / order.length * 2 * Math.PI - Math.PI / 2
                return boxAround(Points.placeOnCircle(center, radius * scale, angle), ...sizes[i])
            }),
        }
    }

    // ─── Switching: one staggered morph for all boxes ─────────────────
    let current = 0
    let animation: RvgAnimation | null = null

    const show = (layout: number, animate: boolean) => {
        current = layout
        const { order, targets } = targetsFor(layout)
        const shapes = order.map(i => boxes[i])
        if (!animate) {
            animation?.cancel()
            shapes.forEach((box, k) => Boxes.copy(targets[k], box))
            return
        }
        animation = Animate.shape.morphAll(shapes, targets, duration, {
            stagger,
            easing: EasingFunctions.easeInOutCubic,
        })
    }
    // A new frame size places the boxes at once, in the current layout.
    Reactive.do([stage], () => show(current, false))

    // ─── Buttons ──────────────────────────────────────────────────────
    const buttons = layouts.map(name => ({
        box:   canvas.visuals.box("button"),
        label: canvas.text.label(name, "button-label"),
    }))
    Reactive.do([rvg.frame], () => {
        const rowWidth = layouts.length * buttonWidth + (layouts.length - 1) * buttonGap
        const start    = Points.move(Segments.midPoint(Boxes.topSide(rvg.frame)), -rowWidth / 2, buttonTop)
        buttons.forEach(({ box, label }, i) => {
            Boxes.box(Points.moveRight(start, i * (buttonWidth + buttonGap)), buttonWidth, buttonHeight, box)
            Boxes.center(box, label)
        })
    })
    const select = (layout: number) => {
        buttons.forEach(({ box, label }, i) => {
            const directive = i === layout ? "@class active" : "@class-remove active"
            box.applyStyleDirective(directive)
            label.applyStyleDirective(directive)
        })
        show(layout, true)
    }
    buttons.forEach(({ box }, i) => Svg.get(box).addEventListener("click", () => select(i)))
    buttons[0].box.applyStyleDirective("@class active")
    buttons[0].label.applyStyleDirective("@class active")
}

Twelve boxes of different sizes that switch between four layouts: scatter, shelf, grid and ring. Animate.shape.morphAll changes position and size of all boxes in one call, and stagger starts them 50 ms apart.

How it works

Each layout is a list of target boxes, one per box on the canvas. Animate.shape.morphAll morphs every box into its target, and stagger delays each start by 50 ms:

const { order, targets } = targetsFor(layout)
const shapes = order.map(i => boxes[i])
animation = Animate.shape.morphAll(shapes, targets, duration, {
    stagger,
    easing: EasingFunctions.easeInOutCubic,
})

The shapes start in the order of the array. Each layout returns its own order: tallest box first on the shelf, row by row in the grid, clockwise from the top on the ring. A target can have a different size than the box, so the boxes in the grid become equal squares on the way.

A new click replaces the running animation; the boxes continue from where they are. When the frame changes size, animation.cancel() stops it and the boxes are placed at once.

API

  • Animate.shape.morphAll: morphs many shapes, one handle for all
  • RvgEasedOptions.stagger: delay between the starts of consecutive shapes
  • Points.placeOnCircle: box centres on the ring
  • Boxes.centeredBox: a target box around a centre

Notes

  • With 12 boxes, 50 ms stagger and 700 ms duration, a switch takes 11 × 50 + 700 = 1250 ms.

See also

  • animations/14-stagger

API used

Also used (23)