CanvasKit WASM
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
-
Module not found: Error: Can't resolve 'fs' in '.../node_modules/canvaskit-wasm/bin/canvaskit.js'
cause Webpack attempts to bundle a Node.js-specific `fs` module usage when targeting a browser environment, as `canvaskit.js` might have conditional imports.fixIn your Webpack configuration, add `node: { fs: 'empty' }` to the configuration object to tell Webpack to ignore the `fs` module in browser builds. -
Failed to load WebAssembly module: CompileError: WebAssembly.instantiate(): expected magic word 00 61 73 6d, found ...
cause The browser or Node.js environment failed to load or compile the `canvaskit.wasm` file, often because `locateFile` provided an incorrect path, or the file was not served correctly.fixVerify that the path provided by the `locateFile` function in `CanvasKitInit` accurately points to the `canvaskit.wasm` file. Ensure the `.wasm` file is correctly placed in your deployment, has correct permissions, and is being served with the `application/wasm` MIME type.
Warnings
- gotcha The `locateFile` function passed to `CanvasKitInit` is critical. It determines how the browser or Node.js locates the `canvaskit.wasm` binary. Incorrect paths will lead to `Failed to load WebAssembly module` errors.
- breaking Webpack users (and similar bundlers) must configure asset handling to copy `canvaskit.wasm` to their build directory, as Webpack typically does not include raw WASM files by default.
- gotcha TypeScript users leveraging modern ESM imports need to enable `resolvePackageJsonExports` in their `tsconfig.json` to properly resolve `canvaskit-wasm`'s subpath exports (e.g., `canvaskit-wasm/full`).
- gotcha The `CanvasKit` object (the main API) is not directly importable or available globally; it is provided as the resolved value of the Promise returned by `CanvasKitInit`.
Install
-
npm install canvaskit-wasm -
yarn add canvaskit-wasm -
pnpm add canvaskit-wasm
Imports
- InitCanvasKit
import { InitCanvasKit } from 'canvaskit-wasm';import InitCanvasKit from 'canvaskit-wasm';
- InitCanvasKit (full bundle)
import { InitCanvasKit } from 'canvaskit-wasm/full';import InitCanvasKit from 'canvaskit-wasm/full';
- CanvasKit (resolved object)
import { CanvasKit } from 'canvaskit-wasm';CanvasKitInit({ /* ... */ }).then((CanvasKit) => { /* use CanvasKit */ }); - InitCanvasKit (CommonJS)
const InitCanvasKit = require('canvaskit-wasm');const InitCanvasKit = require('canvaskit-wasm/bin/canvaskit.js');
Quickstart
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();