Skip to Content
Skia Wasm

Line chart

An animated curve with a gradient under it.

Open in a new tab
import { Skia } from "skia-wasm";

const adapter = await navigator.gpu.requestAdapter();
const device = await adapter!.requestDevice();
const sk = await Skia.init({ device });
const surface = sk.surface(document.querySelector("canvas")!);

const COUNT = 48;
const LEFT = 32;
const RIGHT = 480;
const BOTTOM = 448;

const stroke = sk.paint({
  color: "#3b82f6",
  style: "stroke",
  strokeWidth: 4,
  strokeJoin: "round",
});
const fade = sk.paint({
  shader: sk.linearGradient({
    start: [0, 96],
    end: [0, BOTTOM],
    colors: ["#3b82f6aa", "#3b82f600"],
  }),
});
const grid = sk.paint({
  color: "#cbd5e1",
  style: "stroke",
  strokeWidth: 1,
  pathEffect: sk.pathEffect.dash([4, 4]),
});

// Two paths, emptied and filled again every frame.
const line = sk.path();
const area = sk.path();
const curve = new Float32Array(COUNT * 2);
// The area under the curve is the curve plus two corners, closed.
const outline = new Float32Array((COUNT + 2) * 2);
outline.set([RIGHT, BOTTOM, LEFT, BOTTOM], COUNT * 2);

const frame = (time: number) => {
  const t = time / 1000;
  for (let i = 0; i < COUNT; i++) {
    curve[i * 2] = LEFT + (i / (COUNT - 1)) * (RIGHT - LEFT);
    curve[i * 2 + 1] =
      256 + 80 * Math.sin(i / 6 + t) + 40 * Math.sin(i / 2.5 - t * 1.7);
  }
  outline.set(curve);
  // The points go to wasm in one call each.
  line.reset().addPolygon(curve);
  area.reset().addPolygon(outline, true);

  const canvas = surface.getCanvas();
  canvas.clear("white");
  for (let y = 128; y <= BOTTOM; y += 80) {
    canvas.drawLine(LEFT, y, RIGHT, y, grid);
  }
  canvas.drawPath(area, fade);
  canvas.drawPath(line, stroke);
  surface.flush();
  requestAnimationFrame(frame);
};
requestAnimationFrame(frame);