CanvasKit WASM

0.41.1 · active · verified Wed Apr 22

The `canvaskit-wasm` package provides a WebAssembly (WASM) implementation of Skia's 2D graphics API, enabling high-performance rendering capabilities across diverse JavaScript environments including browsers, Node.js, and WebWorkers. Currently at version 0.41.1, its release cycle generally aligns with updates from the upstream Skia project, which is known for its robust and feature-rich graphics engine. A key differentiator is its ability to offer a comprehensive, portable alternative to native Canvas2D APIs, particularly for complex vectorial graphics, text rendering, and advanced animations like Lottie/Skottie. The package offers several bundles – a default minimal version, a 'full' version including Skottie and other advanced features, and a 'profiling' version – allowing developers to optimize for bundle size and debugging needs. This flexibility, combined with its C++ backend performance via WASM, positions it as a powerful tool for demanding visual applications.

Common errors

Warnings

Install

Imports

Quickstart

Initializes CanvasKit from a CDN, creates a canvas surface, draws a red rectangle, and flushes the drawing to an HTML canvas element.

import InitCanvasKit from 'canvaskit-wasm';

async function setupCanvasKit() {
  // Ensure an HTML canvas element with id 'my-canvas' exists in your page.
  // Example HTML: <canvas id="my-canvas" width="200" height="200"></canvas>
  const CanvasKit = await InitCanvasKit({
    // `locateFile` tells CanvasKit where to find its .wasm file.
    // Using unpkg.com for a quick CDN example.
    locateFile: (file: string) => `https://unpkg.com/canvaskit-wasm@0.41.1/bin/${file}`
  });

  if (!CanvasKit) {
    console.error('Failed to initialize CanvasKit.');
    return;
  }

  // Create a SkSurface attached to the HTML canvas element.
  const surface = CanvasKit.MakeSWCanvasSurface('my-canvas');
  if (!surface) {
    console.error('Could not create SkSurface');
    // Handle error or fallback
    return;
  }
  
  const canvas = surface.getCanvas();
  const paint = new CanvasKit.SkPaint();
  paint.setColor(CanvasKit.RED);
  paint.setStyle(CanvasKit.PaintStyle.Stroke);
  paint.setStrokeWidth(5);
  canvas.drawRect(CanvasKit.SkRect.MakeXYWH(10, 10, 100, 100), paint);
  
  // Flush the SkSurface to render content to the HTML canvas.
  surface.flush();

  // Clean up Skia objects when no longer needed to prevent memory leaks.
  paint.delete();
  surface.delete();
  // Note: CanvasKit itself should only be initialized once.
}

// Execute the setup function.
setupCanvasKit();

view raw JSON →