Skip to Content
OrbixDocs
Block SDK · Guides

Canvas, animation, and workers

Render high-DPI 2D/WebGL canvases, run visibility-aware animation loops, offload compute to Web Workers, and handle files or clipboard writes.

@orbixdocs/sdk includes browser lifecycle hooks that clean up timers, observers, and worker threads automatically when a block unmounts.

High-DPI <canvas> and animation loops

useOrbixCanvas sizes a <canvas> element to its parent container via ResizeObserver and scales its backing store by window.devicePixelRatio. Pair it with useOrbixAnimationLoop for simulations, charts, or interactive visuals:

src/WaveCanvasBlock.tsx
import {
  defineBlock,
  useOrbixAnimationLoop,
  useOrbixCanvas,
  useOrbixTheme,
  type BlockRenderProps,
} from '@orbixdocs/sdk';

export default defineBlock({
  manifest: {
    id: 'acme.wave-monitor',
    name: 'Wave Monitor',
    version: '1.0.0',
    sdk: '^3.0.0',
  },
  component(_props: BlockRenderProps) {
    const { isDark } = useOrbixTheme();
    const { canvasRef, width, height, ready } = useOrbixCanvas({
      contextType: '2d',
      pixelRatio: true,
    });

    const { fps, isRunning, start, stop } = useOrbixAnimationLoop(
      (_deltaMs, elapsedMs) => {
        if (!ready) return;
        const ctx = canvasRef.current?.getContext('2d');
        if (!ctx) return;

        ctx.clearRect(0, 0, width, height);
        ctx.strokeStyle = isDark ? '#ffffff' : '#09090b';
        ctx.lineWidth = 1.5;
        ctx.beginPath();

        const phase = elapsedMs * 0.003;
        for (let x = 0; x <= width; x += 4) {
          const y = height / 2 + Math.sin(x * 0.03 + phase) * (height * 0.28);
          if (x === 0) ctx.moveTo(x, y);
          else ctx.lineTo(x, y);
        }
        ctx.stroke();
      },
      {
        fps: 60,
        pauseWhenHidden: true,
        visibilityTarget: canvasRef,
      }
    );

    return (
      <div
        style={{
          padding: 12,
          borderRadius: 12,
          background: 'var(--orbix-card-bg, #16171b)',
          border: '1px solid var(--orbix-surface-border, #2a2b32)',
          color: 'var(--orbix-text-primary, #f4f4f5)',
        }}
      >
        <div
          style={{
            width: '100%',
            height: 140,
            position: 'relative',
          }}
        >
          <canvas ref={canvasRef} style={{ display: 'block' }} />
        </div>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginTop: 8,
            fontSize: 12,
          }}
        >
          <span>{fps} FPS</span>
          <button
            type="button"
            onClick={() => (isRunning ? stop() : start())}
          >
            {isRunning ? 'Pause' : 'Resume'}
          </button>
        </div>
      </div>
    );
  },
});

Key behaviors:

  • Guard on ready: ready becomes true once ResizeObserver measures a non-zero container size. Wrap <canvas ref={canvasRef}> in a parent with an explicit height (height: 140 or aspectRatio).
  • Automatic suspension: useOrbixAnimationLoop caps deltaMs at 100 ms so slow frames do not destabilize physics math, pauses when the browser tab is hidden (pauseWhenHidden: true), and pauses when visibilityTarget scrolls out of view.
  • 3D libraries: Pass contextType: 'unmanaged' when handing canvasRef.current to Three.js or another renderer that initializes its own WebGL context.

Off-main-thread compute (useWorker and useOrbixWorker)

Use useWorker to run a pure function in a background Web Worker and await its return value, or use useOrbixWorker when posting messages to a self.onmessage handler or external worker URL. Declare workers: ['compute'] when customizing manifest.capabilities:

src/CsvStatsWorker.tsx
import { useState } from 'react';
import { useOrbixWorker, useWorker } from '@orbixdocs/sdk';

interface WorkerInput {
  values: number[];
}

interface WorkerOutput {
  mean: number;
  p95: number;
}

export function StatsRunner({ numbers }: { numbers: number[] }) {
  const [stats, setStats] = useState<WorkerOutput | null>(null);

  const worker = useWorker<WorkerInput, WorkerOutput>((data) => {
    const sorted = [...data.values].sort((a, b) => a - b);
    if (sorted.length === 0) return { mean: 0, p95: 0 };
    const sum = sorted.reduce((acc, n) => acc + n, 0);
    const idx = Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95));
    return { mean: sum / sorted.length, p95: sorted[idx] };
  });

  const streamWorker = useOrbixWorker<number[], number>(
    (e: MessageEvent<number[]>) => {
      const total = e.data.reduce((a, b) => a + b, 0);
      self.postMessage(total);
    },
    { timeout: 5000 }
  );

  return (
    <div>
      <button
        type="button"
        onClick={async () => {
          const res = await worker.run({ values: numbers });
          setStats(res);
          streamWorker.postMessage(numbers);
        }}
      >
        Compute p95
      </button>
      {stats && (
        <span>
          {' '}Mean: {stats.mean.toFixed(2)} · P95: {stats.p95.toFixed(2)}
        </span>
      )}
      {streamWorker.lastResult !== null && (
        <span> · Sum: {streamWorker.lastResult}</span>
      )}
    </div>
  );
}

Inline worker functions cannot close over outer variables

When you pass a function to useWorker or useOrbixWorker, the SDK serializes fn.toString() into a Blob URL and revokes it on unmount. Do not reference imports or outer React state inside the worker function; pass all required inputs through worker.run(data) or postMessage(data).

File uploads and clipboard writes

  • useOrbixFileUpload(options?): Uploads a File through the host's asset storage adapter (bucket defaults to 'block-assets') and returns { upload, isUploading, progress, lastResult, error }.
  • useClipboard(timeoutMs?): Copies text via navigator.clipboard.writeText and flips copied back to false after timeoutMs (default 2000 ms). Requires clipboard: ['write'] in manifest.capabilities.
src/CopyAndUpload.tsx
import { useClipboard, useOrbixFileUpload } from '@orbixdocs/sdk';

export function AssetLinkUploader() {
  const { upload, isUploading, lastResult } = useOrbixFileUpload();
  const { copy, copied } = useClipboard(1500);

  return (
    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
      <input
        type="file"
        disabled={isUploading}
        onChange={(e) => {
          const file = e.target.files?.[0];
          if (file) void upload(file);
        }}
      />
      {lastResult?.url && (
        <button type="button" onClick={() => void copy(lastResult.url)}>
          {copied ? 'Copied URL' : 'Copy asset URL'}
        </button>
      )}
    </div>
  );
}

On this page