Node canvas is a Cairo backed Canvas implementation for NodeJS.
Node canvas is a Cairo backed Canvas implementation for NodeJS.
node-canvas is a Cairo-backed Canvas implementation for Node.js.
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.
$ npm install canvas@nextTo get v3:
$ npm install canvasThe minimum version of Node.js required is 22.
Binaries will be installed for the following platforms:
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.
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('')
})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.
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.)
const { createCanvas } = require('canvas')
const mycanvas = createCanvas(200, 200)
const myPDFcanvas = createCanvas(600, 800, 'pdf') // see "PDF Support" sectioncreateImageData(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.
const { createImageData } = require('canvas')
const width = 20, height = 20
const arraySize = width * height * 4
const mydata = createImageData(new Uint8ClampedArray(arraySize), width)loadImage() => Promise<Image>
Convenience method for loading images. This method works in both Node.js and Web browsers.
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 imageinterface 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.
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'.
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.
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()
})
})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.
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.
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 trackedIf 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((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.
raw or for PDF or SVG canvases.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.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.
…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.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:
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(config?: any) => ReadableStrea
actualBoundingBoxLeft has the sign inverted relative to canvas's own rasteriser (3.2.0, 3.2.3)
`ImageData` support "rgba-float16" pixelFormat (Float16Array)
The PDF file created by createPDFStream becomes larger in size, and createWriteStream is very slow
v4.0.0-rc3: SVG text rendering not working
Discussion of more standard interface between Canvas and wxWidgets
Support more backends
Garbled of chinese
Add support for EGL drawing context
Mask on item over path are not correct.
fbdev backend