Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

node-canvas

> 编程语言
Open source

Node canvas is a Cairo backed Canvas implementation for NodeJS.

10.7K stars0 likes0 views
WebsiteGitHub

About

Node canvas is a Cairo backed Canvas implementation for NodeJS.

node-canvas

node-canvas is a Cairo-backed Canvas implementation for Node.js.

Installation

The latest version of node-canvas is v4. It fixes a plethora of font related issues, adds support for worker threads, reduces binary size, removes the post install script, expands the platforms that binaries support, and more. It is still in the pre-release phase. We appreciate any feedback.

bash
$ npm install canvas@next

To get v3:

bash
$ npm install canvas

The minimum version of Node.js required is 22.

Binaries will be installed for the following platforms:

  • macOS x64/arm64
  • Linux x64/x86/arm64 (glibc or musl)
  • Linux arm/riscv64 (glibc)
  • Windows x64/x86/arm64

If you want to install for a more exotic system, CD into the package and run zig build. You may need to tweak build.zig. PRs are welcome.

Quick Example

javascript
const { createCanvas, loadImage } = require('canvas')
const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d')

// Write "Awesome!"
ctx.font = '30px Impact'
ctx.rotate(0.1)
ctx.fillText('Awesome!', 50, 100)

// Draw line under text
var text = ctx.measureText('Awesome!')
ctx.strokeStyle = 'rgba(0,0,0,0.5)'
ctx.beginPath()
ctx.lineTo(50, 102)
ctx.lineTo(50 + text.width, 102)
ctx.stroke()

// Draw cat with lime helmet
loadImage('examples/images/lime-cat.jpg').then((image) => {
  ctx.drawImage(image, 50, 0, 70, 70)

  console.log('')
})

Documentation

This project is an implementation of the Web Canvas API and implements that API as closely as possible. For API documentation, please visit Mozilla Web Canvas API. (See Compatibility Status for the current API compliance.) All utility methods and non-standard APIs are documented below.

Utility methods

  • createCanvas()
  • createImageData()
  • loadImage()

Font API

  • FontFace
  • fonts

Non-standard APIs

  • Image#src
  • Image#dataMode
  • Canvas#toBuffer()
  • Canvas#createPNGStream()
  • Canvas#createJPEGStream()
  • Canvas#createPDFStream()
  • Canvas#toDataURL()
  • CanvasRenderingContext2D#patternQuality
  • CanvasRenderingContext2D#quality
  • CanvasRenderingContext2D#textDrawingMode
  • CanvasRenderingContext2D#globalCompositeOperation = 'saturate'
  • CanvasRenderingContext2D#antialias

createCanvas()

typescript
createCanvas(width: number, height: number, type?: 'PDF'|'SVG') => Canvas

Creates a Canvas instance. This method works in both Node.js and Web browsers, where there is no Canvas constructor. (See browser.js for the implementation that runs in browsers.)

javascript
const { createCanvas } = require('canvas')
const mycanvas = createCanvas(200, 200)
const myPDFcanvas = createCanvas(600, 800, 'pdf') // see "PDF Support" section

createImageData()

typescript
createImageData(width: number, height: number) => ImageData
createImageData(data: Uint8ClampedArray, width: number, height?: number) => ImageData
// for alternative pixel formats:
createImageData(data: Uint16Array, width: number, height?: number) => ImageData

Creates an ImageData instance. This method works in both Node.js and Web browsers.

javascript
const { createImageData } = require('canvas')
const width = 20, height = 20
const arraySize = width * height * 4
const mydata = createImageData(new Uint8ClampedArray(arraySize), width)

loadImage()

typescript
loadImage() => Promise<Image>

Convenience method for loading images. This method works in both Node.js and Web browsers.

javascript
const { loadImage } = require('canvas')
const myimg = loadImage('http://server.com/image.png')

myimg.then(() => {
  // do something with image
}).catch(err => {
  console.log('oh no!', err)
})

// or with async/await:
const myimg = await loadImage('http://server.com/image.png')
// do something with image

FontFace

typescript

interface FontFaceDescriptors {
  weight?: string | number;
  style?: string;
}

class FontFace {
  constructor(
    family: string,
    source: string | ArrayBuffer | Uint8Array,
    descriptors?: FontFaceDescriptors
  )

  family: string;
  style: string;
  weight: string;
  status: 'loaded' | 'unloaded' | 'error';
}

To use your own font file, create a FontFace with the file path and add it to fonts. fonts is just like the browser's document.fonts, but with a slightly more limited API.

javascript
const { createCanvas, FontFace, fonts } = require('canvas')
fonts.add(new FontFace('Comic Sans', '/home/you/comicsans.ttf'))

const canvas = createCanvas(500, 500)
const ctx = canvas.getContext('2d')

ctx.font = '12px "Comic Sans"'
ctx.fillText('Everyone hates this font :(', 250, 10)

The second argument can either be a path to the font file or a buffer in TrueType format. The third argument is an object with properties that resemble the CSS properties that are specified in @font-face rules. You must specify at least family. weight and style are optional and default to 'normal'.

fonts

typescript

class FontFaceSet {
  add(face: FontFace): void;
  has(face: FontFace): boolean;
  clear(): void;
  delete(face: FontFace): boolean;
  [Symbol.iterator](): Iterator<FontFace>;
  size: number;
}

fonts: FontFaceSet

fonts implements a subset of the browser's document.fonts. Use fonts.delete() to unregister an individual font, or fonts.clear() to remove all registered fonts. This is useful when you want to remove all registered fonts, such as when using the canvas in tests.

typescript
const { registerFont, createCanvas, fonts, FontFace } = require('canvas')

describe('text rendering', () => {
  afterEach(() => {
    fonts.clear()
  })
  it('should render text with Comic Sans', () => {
    fonts.add(new FontFace('Comic Sans', '/home/you/comicsans.ttf'))

    const canvas = createCanvas(500, 500)
    const ctx = canvas.getContext('2d')

    ctx.font = '12px "Comic Sans"'
    ctx.fillText('Everyone loves this font :)', 250, 10)

    // assertScreenshot()
  })
})

Image#src

typescript
img.src: string|Buffer

As in browsers, img.src can be set to a data: URI or a remote URL. In addition, node-canvas allows setting src to a local file path or Buffer instance.

…

Note: In some cases, img.src= is currently synchronous. However, you should always use img.onload and img.onerror, as we intend to make img.src= always asynchronous as it is in browsers. See https://github.com/Automattic/node-canvas/issues/1007.

Image#dataMode

typescript
img.dataMode: number

Applies to JPEG images drawn to PDF canvases only.

Setting img.dataMode = Image.MODE_MIME or Image.MODE_MIME|Image.MODE_IMAGE enables MIME data tracking of images. When MIME data is tracked, PDF canvases can embed JPEGs directly into the output, rather than re-encoding into PNG. This can drastically reduce filesize and speed up rendering.

javascript
const { Image, createCanvas } = require('canvas')
const canvas = createCanvas(w, h, 'pdf')
const img = new Image()
img.dataMode = Image.MODE_IMAGE // Only image data tracked
img.dataMode = Image.MODE_MIME // Only mime data tracked
img.dataMode = Image.MODE_MIME | Image.MODE_IMAGE // Both are tracked

If working with a non-PDF canvas, image data must be tracked; otherwise the output will be junk.

Enabling mime data tracking has no benefits (only a slow down) unless you are generating a PDF.

Canvas#toBuffer()

typescript
canvas.toBuffer((err: Error|null, result: Buffer) => void, mimeType?: string, config?: any) => void
canvas.toBuffer(mimeType?: string, config?: any) => Buffer

Creates a Buffer object representing the image contained in the canvas.

  • callback If provided, the buffer will be provided in the callback instead of being returned by the function. Invoked with an error as the first argument if encoding failed, or the resulting buffer as the second argument if it succeeded. Not supported for mimeType raw or for PDF or SVG canvases.
  • mimeType A string indicating the image format. Valid options are image/png, image/jpeg, raw (unencoded data in BGRA order on little-endian (most) systems, ARGB on big-endian systems; top-to-bottom), application/pdf (for PDF canvases) and image/svg+xml (for SVG canvases). Defaults to image/png for image canvases, or the corresponding type for PDF or SVG canvas.
  • config
    • For image/jpeg, an object specifying the quality (0 to 1), if progressive compression should be used and/or if chroma subsampling should be used: {quality: 0.75, progressive: false, chromaSubsampling: true}. All properties are optional.

    • For image/png, an object specifying the ZLIB compression level (between 0 and 9), the compression filter(s), the palette (indexed PNGs only), the the background palette index (indexed PNGs only) and/or the resolution (ppi): {compressionLevel: 6, filters: canvas.PNG_ALL_FILTERS, palette: undefined, backgroundIndex: 0, resolution: undefined}. All properties are optional.

      Note that the PNG format encodes the resolution in pixels per meter, so if you specify 96, the file will encode 3780 ppm (~96.01 ppi). The resolution is undefined by default to match common browser behavior.

    • For application/pdf, an object specifying optional document metadata: {title: string, author: string, subject: string, keywords: string, creator: string, creationDate: Date, modDate: Date}. All properties are optional and default to undefined, except for creationDate, which defaults to the current date.

      For a description of these properties, see page 550 of PDF 32000-1:2008.

      Note that there is no standard separator for keywords. A space is recommended because it is in common use by other applications, and Cairo will enclose the list of keywords in quotes if a comma or semicolon is used.

Return value

If no callback is provided, a Buffer. If a callback is provided, none.

Examples

…

Canvas#createPNGStream()

typescript
canvas.createPNGStream(config?: any) => ReadableStream

Creates a ReadableStream that emits PNG-encoded data.

  • config An object specifying the ZLIB compression level (between 0 and 9), the compression filter(s), the palette (indexed PNGs only) and/or the background palette index (indexed PNGs only): {compressionLevel: 6, filters: canvas.PNG_ALL_FILTERS, palette: undefined, backgroundIndex: 0, resolution: undefined}. All properties are optional.

Examples

javascript
const fs = require('fs')
const out = fs.createWriteStream(__dirname + '/test.png')
const stream = canvas.createPNGStream()
stream.pipe(out)
out.on('finish', () =>  console.log('The PNG file was created.'))

To encode indexed PNGs from canvases with pixelFormat: 'A8' or 'A1', provide an options object:

javascript
const palette = new Uint8ClampedArray([
  //r    g    b    a
    0,  50,  50, 255, // index 1
   10,  90,  90, 255, // index 2
  127, 127, 255, 255
  // ...
])
canvas.createPNGStream({
  palette: palette,
  backgroundIndex: 0 // optional, defaults to 0
})

Canvas#createJPEGStream()

typescript
canvas.createJPEGStream(config?: any) => ReadableStrea

Issues· 420 open

View all issuesOpen on GitHub
  • #2620

    actualBoundingBoxLeft has the sign inverted relative to canvas's own rasteriser (3.2.0, 3.2.3)

    BugUpdated Sep 7, 2026
  • #2621

    `ImageData` support "rgba-float16" pixelFormat (Float16Array)

    FeatureUpdated Sep 2, 2026
  • #2615

    The PDF file created by createPDFStream becomes larger in size, and createWriteStream is very slow

    BugUpdated Sep 2, 2026
  • #2619

    v4.0.0-rc3: SVG text rendering not working

    BugUpdated Aug 30, 2026
  • #2616

    Discussion of more standard interface between Canvas and wxWidgets

    Updated Aug 22, 2026
  • #382

    Support more backends

    FeatureUpdated Aug 22, 2026
  • #461

    Garbled of chinese

    Text & FontsUpdated Aug 22, 2026
  • #478

    Add support for EGL drawing context

    FeatureUpdated Aug 22, 2026
  • #504

    Mask on item over path are not correct.

    BugUpdated Aug 22, 2026
  • #533

    fbdev backend

    FeatureUpdated Aug 22, 2026

> Tags

JavaScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言