Soundor

Canvas

Pixels code draws, with a 2D or a WebGL 2 context.

A Canvas is pixels your code draws, like an HTML <canvas>: get its context from its node, in an effect or on every frame.

import {
  Canvas,
  useAnimationFrame,
  useCanvasSize,
  useParameter,
} from '@soundor/react';
import { useRef } from 'react';
import { parameters } from 'soundor:parameters';
import type { UiNode } from 'soundor:ui';

const WIDTH = 320;
const HEIGHT = 120;

// A canvas drawn every frame: a wave as tall as the gain parameter.
export default function Wave() {
  const canvas = useRef<UiNode>(null);
  const gain = useParameter(parameters.gain);
  // The buffer is exactly the device pixels the box covers: it stays sharp.
  const size = useCanvasSize(canvas);

  useAnimationFrame((time) => {
    const context = canvas.current?.getContext('2d');
    if (!context || size.width === 0) return;
    // Draw in the box's own units.
    context.setTransform(size.scaleX, 0, 0, size.scaleY, 0, 0);
    context.fillStyle = '#17181c';
    context.fillRect(0, 0, WIDTH, HEIGHT);
    context.strokeStyle = '#3a7bfd';
    context.lineWidth = 2;
    context.beginPath();
    for (let x = 0; x <= WIDTH; x += 2) {
      const phase = x / 24 - time / 300;
      const y = HEIGHT / 2 - Math.sin(phase) * gain * (HEIGHT / 2 - 4);
      if (x === 0) context.moveTo(x, y);
      else context.lineTo(x, y);
    }
    context.stroke();
  });

  return (
    <Canvas
      ref={canvas}
      style={{ width: WIDTH, height: HEIGHT, borderRadius: 8 }}
    />
  );
}
canvas.tsxSource
  • Contexts: ref.current.getContext('2d') gives a CanvasRenderingContext2D (drawn with Skia natively), the same object every time. getContext('webgl2') gives a WebGL2RenderingContext on the GPU, or null where there is no acceptable GPU; Three.js runs on it unmodified.
  • Size: width and height are the drawing buffer's, 300 by 150 by default, and the buffer is stretched over the box. Setting either clears the canvas, so draw again after. For crisp lines, use useCanvasSize: give the canvas a size by its style or by flexbox, and it keeps the buffer exactly the device pixels the box covers. That holds at any display scale, through the host's scaling and an editor's zoom, and whatever resizes the box, and it re-renders when the size changes. Without a style, the box is the buffer's size in logical pixels.
  • Every frame: useAnimationFrame calls your drawing code before each frame, while the component is mounted (hooks).
  • What 2D draws: paths, rectangles, text, gradients, patterns, images, ImageData, transforms and compositing. Shadows, filter, Path2D and DOMMatrix throw rather than draw something else: see the canvas reference.
  • To assistive technology a canvas is decorative unless it is given a label, a role or accessible, like an image.

Props

Prop

Type

Canvas also takes the event props and the accessibility props.

On this page