# `skr canvas` [![CI](https://github.com/Brooooooklyn/canvas/actions/workflows/CI.yaml/badge.svg)](https://github.com/Brooooooklyn/canvas/actions/workflows/CI.yaml) ![Skia Version](https://img.shields.io/badge/Skia-chrome%2Fm157-hotpink) [![Downloads](https://img.shields.io/npm/dm/@napi-rs/canvas.svg?sanitize=true)](https://npmcharts.com/compare/@napi-rs/canvas?minimal=true) > πŸš€ Help me to become a full-time open-source developer by [sponsoring me on Github](https://github.com/sponsors/Brooooooklyn) Google Skia binding to Node.js via [Node-API](https://napi.rs), **0 System dependencies!** [δΈ­ζ–‡ζ–‡ζ‘£](./README-zh.md) # Install ```bash yarn add @napi-rs/canvas npm install @napi-rs/canvas ``` # Support matrix ## System requirement ### `arm64` [**_cortex-a57_**](https://en.wikipedia.org/wiki/ARM_Cortex-A57) or newer CPU architecture on **Linux**. All Apple M chips on **macOS**. ### `armv7` [**_cortex-a7_**](https://en.wikipedia.org/wiki/ARM_Cortex-A7) or newer CPU architecture. ### glibc Since Skia relies on the [glibc](https://www.gnu.org/software/libc/) 2.18 API, you need to have at least glibc version >= 2.18 on your system. Note: the armv7 (`linux-arm-gnueabihf`) packages from 0.1.66 to 1.1.0 need a newer glibc (0.1.66 needs 2.28, 1.1.0 needs 2.30). Later versions need glibc 2.18, like the other targets. ## AWS Lambda usage To use this library on Lambda you will need to use a Lambda layer. You can simply attach a lambda layer by getting an ARN from [Canvas-Lambda-Layer](https://github.com/ShivamJoker/Canvas-Lambda-Layer) > Make sure to exclude `@napi-rs/canvas` while bundling your Lambda. # Usage ```js const { promises } = require('node:fs') const { join } = require('node:path') const { createCanvas, loadImage } = require('@napi-rs/canvas') const canvas = createCanvas(300, 320) const ctx = canvas.getContext('2d') ctx.lineWidth = 10 ctx.strokeStyle = '#03a9f4' ctx.fillStyle = '#03a9f4' // Wall ctx.strokeRect(75, 140, 150, 110) // Door ctx.fillRect(130, 190, 40, 60) // Roof ctx.beginPath() ctx.moveTo(50, 140) ctx.lineTo(150, 60) ctx.lineTo(250, 140) ctx.closePath() ctx.stroke() async function main() { // load images from disk or from a URL const catImage = await loadImage('path/to/cat.png') const dogImage = await loadImage('https://example.com/path/to/dog.jpg') ctx.drawImage(catImage, 0, 0, catImage.width, catImage.height) ctx.drawImage(dogImage, canvas.width / 2, canvas.height / 2, dogImage.width, dogImage.height) // export canvas as image const pngData = await canvas.encode('png') // JPEG, AVIF and WebP are also supported // encoding in libuv thread pool, non-blocking await promises.writeFile(join(__dirname, 'simple.png'), pngData) } main() ``` ![](./example/simple.png) ## Image metadata `toBuffer`, `encode` and `encodeSync` can write the resolution (DPI) and a few text fields into PNG and JPEG output. Put them in the options object: ```js const png = canvas.toBuffer('image/png', { resolution: 300, // pixels per inch, the same option as node-canvas title: 'Floor plan', author: 'Jane Doe', description: 'Ground floor, 1:100', }) // JPEG: use encode / encodeSync to set the quality as well const jpeg = await canvas.encode('jpeg', { quality: 90, resolution: 300, copyright: 'Β© 2026 Jane Doe' }) ``` | Option | PNG | JPEG | | ------------- | ------------------ | ---------------------------- | | `resolution` | `pHYs` chunk | JFIF density (dots per inch) | | `title` | `Title` text chunk | XMP `dc:title` | | `author` | `Author` | XMP `dc:creator` | | `description` | `Description` | XMP `dc:description` | | `copyright` | `Copyright` | XMP `dc:rights` | | `software` | `Software` | XMP `xmp:CreatorTool` | | `comment` | `Comment` | `COM` segment | WebP, AVIF and GIF output ignore these options. `toDataURL`, `toDataURLAsync`, `toBlob`, `convertToBlob`, `encodeStream` and `savePng` never write metadata. To save a file with metadata, write the Buffer from `toBuffer` or `encode`. With an options object, `toBuffer('image/jpeg', ...)` encodes at quality 92; use `encode` or `encodeSync` for another quality. ### PNG encoding options For PNG output, `toBuffer('image/png', options)`, `encode('png', options)` and `encodeSync('png', options)` also accept `compressionLevel` (zlib level `0–9`, default `6`) and `filters` (libpng row filter bitmask from `PngFilter`, default `PngFilter.All` / `0xF8`) in the same options object: ```js const { createCanvas, PngFilter } = require('@napi-rs/canvas') // Fast PNG encoding (Chromium's canvas preset: zlib level 1, Up filter only) const png = await canvas.encode('png', { compressionLevel: 1, filters: PngFilter.Up, // 0x20 }) ``` | `PngFilter` constant | Value | Description | | -------------------- | ------ | --------------------- | | `PngFilter.None` | `0x08` | None filter | | `PngFilter.Sub` | `0x10` | Sub filter | | `PngFilter.Up` | `0x20` | Up filter | | `PngFilter.Avg` | `0x40` | Average filter | | `PngFilter.Paeth` | `0x80` | Paeth filter | | `PngFilter.All` | `0xF8` | All filters (default) | ## Text rendering By default text is drawn the same way on every OS. Every font is drawn with FreeType, with Skia's default text gamma, no LCD (subpixel) text and one font family table (the one Linux uses). Text gives the same pixels and the same `measureText` results on macOS, Linux and Windows when all of these are true: 1. `ctx.font` names only fonts you registered. The canvas default `10px sans-serif`, the other generic families and names like `Arial` use installed fonts, unless you registered a font under that name. 2. Your registered fonts have every character you draw. A character they lack is taken from an installed font. 3. You set `ctx.lang`, for example to `'en'`. The default `'inherit'` follows the host language. 4. You use the default `'portable'` renderer, not `setTextRenderer('system')`. 5. The `FREETYPE_PROPERTIES` env var is not set. x64 and arm64 builds can still differ by 1 color level on some edge pixels. ```js const { GlobalFonts } = require('@napi-rs/canvas') // A name no OS installs GlobalFonts.registerFromPath('./fonts/Lato-Regular.ttf', 'MyLato') ctx.font = '20px MyLato' ctx.lang = 'en' ``` A name registered over an installed family (for example `Helvetica`) works like a CSS `@font-face` in Chrome: only font lists that name it use it, for every style (the faces are chosen as described below; bold or italic is made from the chosen face when that file is not bold or italic). The generic families, such as `sans-serif`, keep the installed family. To change a generic family, register the font under the keyword itself: ```js GlobalFonts.registerFromPath('./fonts/Lato-Regular.ttf', 'sans-serif') ``` For the unquoted keyword (`sans-serif`), each face of that font is matched by the file's own style and descriptors are ignored; bold is made from weight 600, as for other registered fonts. Only the quoted name (`"sans-serif"`) follows the descriptor and newest-face rule below. Faces of one family are chosen by their descriptors, as with `@font-face`. Without descriptors every face is `auto` and the newest face wins; give `{ weight, style, stretch }` for each file of a family, or use `loadFontsFromDir` (installed fonts match by the file's own style): ```js GlobalFonts.registerFromPath('./fonts/Lato-Regular.ttf', 'MyLato', { weight: 400 }) GlobalFonts.registerFromPath('./fonts/Lato-Bold.ttf', 'MyLato', { weight: 700 }) ``` > **Behavior change**: registered faces with no descriptors are all `auto`, so in such a family the face registered last draws every style (made bold or italic when that file is not), as Chrome draws `@font-face` rules with no descriptors. Before, each face was picked by the file's own style. These still depend on the OS and the machine: - Installed fonts. Names like `Arial` or `Helvetica`, and the generic families (`sans-serif`, `serif`, `monospace`, `system-ui`, the canvas default `10px sans-serif`) resolve to whatever is installed. - Characters your registered fonts lack. They are taken from an installed font (the ones `loadSystemFonts` and `loadFontsFromDir` load, or the OS font folder) that has them, else they draw as boxes. A font you `register` or `registerFromPath` is never used for a character another font lacks, as in Chrome: to give a host without fonts a fallback font, load it with `loadFontsFromDir`. - The `ex`, `ch`, `cap` and line-height units inside SVG images use an installed default font. - Lottie (Skottie) text uses installed fonts. - PDF font embedding depends on the build target. - x64 and arm64 builds can differ by 1 color level on some edge pixels. - A `FREETYPE_PROPERTIES` env var changes FreeType's hinting. - The host language. The default `ctx.lang` (`'inherit'`) follows the OS UI language (the macOS language list, the Windows user locale, or `LANGUAGE` / `LC_ALL` / `LC_MESSAGES` / `LANG` elsewhere), as Chrome does. It changes `locl` glyphs, case mapping (`small-caps` under `tr`) and CJK punctuation spacing. Set `ctx.lang` (for example `'en'`) to pin it. The installed font picked for a Han character still follows the host language unless `ctx.lang` names a CJK language (for example `'ja'` or `'zh-Hans'`). On macOS with `setTextRenderer('system')`, the generic families also follow a `ja`, `ko`, `zh-CN`, `zh-TW`, `ar`, `he` or `fa` UI language whatever `ctx.lang` is, as in Chrome (`serif` is Hiragino Mincho ProN under a Japanese UI). Set `DISABLE_SYSTEM_FONTS_LOAD=1` to keep installed fonts out of `GlobalFonts.families`. By default they can still be found by name, on every OS. ### `setTextRenderer()` `setTextRenderer('system')` draws text the way Chrome does on each OS: CoreText on macOS (with CoreText's installed fonts and fallback), Fontations on Linux and DirectWrite on Windows (with Fontations for color/CFF2/avar2 web fonts), plus each OS's text gamma, LCD text on opaque macOS canvases, Chrome's per-OS font families and the macOS metric rules. This was the default on macOS and Linux in 1.0.12 and 1.0.13. `'portable'` is the default. ```js const { setTextRenderer, getTextRenderer } = require('@napi-rs/canvas') setTextRenderer('system') getTextRenderer() // 'system' ``` It applies to the whole process. Call it once at startup, before you create canvases. `setTextRenderer('portable')` switches back. Any other value throws a `TypeError`. A canvas created before the switch keeps its old text gamma until you set its width or height. A `ctx.font` value set before the switch keeps its parsed form (sizes in `ex`, `ch` and other font-relative units, and on macOS the `BlinkMacSystemFont` to `system-ui` rewrite), so set `ctx.font` again after the switch. > **Behavior change** ([#1402](https://github.com/Brooooooklyn/canvas/issues/1402)): text on macOS and Linux is drawn the way Windows draws it, so pixels and `measureText` results differ from 1.0.12 and 1.0.13. On macOS, the installed fonts are FreeType faces again (as in 1.0.11), read from `/System/Library/Fonts`, `/Library/Fonts` and `~/Library/Fonts`; CoreText's per-character fallback is off, and `sans-serif`, `serif` and `monospace` map to Arial, Times New Roman and the Linux monospace list. On macOS, `DISABLE_SYSTEM_FONTS_LOAD` no longer hides installed fonts from name lookup, as on Linux and Windows and before 1.0.12; it only keeps them out of `GlobalFonts.families`. Call `setTextRenderer('system')` to draw with each OS's own font renderer and installed fonts again, as 1.0.12 and 1.0.13 did. Both renderers now shape text the way Chrome does, so the output is not the same as in 1.0.12 and 1.0.13. > **Behavior change**: a character no font of the font list has is taken from an installed font, as Chrome's font cache takes it from the platform's fonts. This applies to the portable renderer on every OS and to the system renderer off macOS (on macOS, CoreText still picks first). The font is chosen the way Chrome on Windows chooses it: a bold or italic list first tries its first family at the normal style, then the font Windows names for the character's script (on macOS, the font Chrome's CoreText fallback names for it), then the first installed family, by name, that has the character. Before, such a character drew as a box (the first font's `.notdef`). Private use characters still draw as boxes. > **Behavior change**: SVG text (SVG images, the SVG images nested in them, and `convertSVGTextToPath`) takes a character its first font lacks from the next family of its `font-family` list, then from the system's fonts, as canvas text does. Chrome does the same. Before, the whole text used the first font, and a character it lacks drew as a box. Text with no such character draws the same as before. `convertSVGTextToPath` now reads the document the way an SVG image does (`