Soundorv0.13.0

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, 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);

  useAnimationFrame((time) => {
    const context = canvas.current?.getContext('2d');
    if (!context) return;
    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}
      width={WIDTH}
      height={HEIGHT}
      style={{ 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. Setting either clears the canvas, so draw again after. The box is the buffer's size in logical pixels unless styled, and the buffer is stretched over it: size the buffer by devicePixelRatio for crisp lines.
  • 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