### Install Cairo from Source
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
Download, extract, configure, and install cairo. Ensure dependencies like libpng are correctly installed.
```shell
curl -L http://www.cairographics.org/releases/cairo-1.12.18.tar.xz -o cairo.tar.xz
tar -xf cairo.tar.xz && cd cairo-1.12.18
./configure --prefix=/usr/local --disable-dependency-tracking
make install
```
--------------------------------
### Install pkg-config from Source
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
Download, extract, configure, and install pkg-config from source if it's not already available.
```shell
curl https://pkg-config.freedesktop.org/releases/pkg-config-0.28.tar.gz -o pkgconfig.tgz
tar -zxf pkgconfig.tgz && cd pkg-config-0.28
./configure && make install
```
--------------------------------
### Install node-canvas using npm
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Ubuntu-and-other-Debian-based-systems
After installing the system dependencies, use npm to install the node-canvas package into your project.
```bash
$ npm install canvas
```
--------------------------------
### Install Dependencies with Homebrew
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
Use Homebrew to install necessary dependencies for cairo, including optional image format support.
```shell
brew install pkg-config cairo pango libpng jpeg giflib librsvg
```
--------------------------------
### Install Pixman from Source
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
Download, extract, configure, and install pixman, a dependency of cairo. Ensure to use a release version >= 0.34.0 if encountering MMX-related errors.
```shell
curl -L http://www.cairographics.org/releases/pixman-0.30.0.tar.gz -o pixman.tar.gz
tar -zxf pixman.tar.gz && cd pixman-0.30.0/
./configure --prefix=/usr/local --disable-dependency-tracking
make install
```
```shell
curl -L http://www.cairographics.org/releases/pixman-0.34.0.tar.gz -o pixman.tar.gz
tar -zxf pixman.tar.gz && cd pixman-0.34.0/
```
--------------------------------
### Quick Example: Drawing on Canvas
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
A basic example demonstrating how to create a canvas, draw text, measure text width, draw a line, and load an image using node-canvas.
```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('
')
})
```
--------------------------------
### Install Node-Canvas Dependencies and Package on Linux
Source: https://github.com/automattic/node-canvas/wiki/Installation:-AWS-Lambda
Installs system libraries required by node-canvas and then installs the canvas package itself using npm. This is a prerequisite for building the canvas binary on a Linux environment compatible with AWS Lambda.
```bash
sudo yum install cairo-devel libjpeg-turbo-devel giflib-devel pango-devel -y
npm install canvas@next
```
--------------------------------
### Install Dependencies with Yum
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Fedora-and-other-RPM-based-distributions
Installs essential development tools and libraries required for building node-canvas on RPM-based systems. Ensure you have sudo privileges.
```shell
$ sudo yum install gcc-c++ cairo-devel libjpeg-turbo-devel pango-devel giflib-devel
```
--------------------------------
### Install GIF and JPEG Support with Homebrew
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
Install giflib and libjpeg using Homebrew if you encounter errors related to GIF or JPEG image support, then recompile node-canvas.
```shell
brew install giflib # for .gif files
```
```shell
brew install libjpeg # for .jpg files
```
--------------------------------
### Build node-canvas from source
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
To build node-canvas from source, use the --build-from-source flag with npm install. Ensure you have the necessary dependencies installed.
```bash
npm install --build-from-source
```
--------------------------------
### Install Cairo and Dependencies with Pacman
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Windows-(using-MSYS2)
Use pacman within the MSYS2 shell to install the Cairo library and essential tools for creating Visual Studio compatible import libraries.
```bash
pacman -S mingw64/mingw-w64-x86_64-cairo
pacman -S mingw64/mingw-w64-x86_64-binutils mingw64/mingw-w64-x86_64-tools
```
--------------------------------
### Install Dependencies with MacPorts
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
Use MacPorts to install necessary dependencies for cairo, including optional image format support.
```shell
port install pkgconfig cairo pango libpng jpeg giflib librsvg
```
--------------------------------
### Update Package Lists and Install Dependencies
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Ubuntu-and-other-Debian-based-systems
Run these commands to update your system's package list and install necessary build tools and libraries for node-canvas. Some libraries are optional and enable specific image format support.
```bash
$ sudo apt-get update
$ sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev
```
--------------------------------
### Install System Dependencies for node-canvas
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Arch-based-distributions
Update package lists and install essential development tools and libraries required for node-canvas. Optional libraries for specific image format support can be included.
```sh
sudo pacman -Syu
sudo pacman -S base-devel cairo pango libjpeg-turbo giflib libsvgtiny
```
--------------------------------
### Install Node.js and Development Tools on EC2 for Lambda
Source: https://github.com/automattic/node-canvas/wiki/Installation:-AWS-Lambda
Installs necessary development tools and Node.js versions (6.10 or 8.10) on an EC2 instance, which is required for building node-canvas for AWS Lambda.
```bash
sudo yum groupinstall "Development Tools" -y
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
# Exit SSH session and reopen here to make nvm available
# Node 6.10:
nvm install 6.10
# Or Node 8.10:
nvm install 8.10
```
--------------------------------
### Set PKG_CONFIG_PATH for Homebrew Cairo with X11
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
If Cairo was installed with Homebrew and X11 is involved, adjust PKG_CONFIG_PATH to include both Homebrew and X11 pkgconfig directories.
```shell
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:/opt/X11/lib/pkgconfig
```
--------------------------------
### Search and Install Fonts with Yum
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Fedora-and-other-RPM-based-distributions
Searches for available Arial fonts and installs the Liberation Sans font package, which can be used as a substitute. This is useful for applications that require specific font families.
```shell
yum search arial
yum install liberation-sans-fonts.noarch
```
--------------------------------
### Generate Library Files with Node.js Script
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Windows-(using-MSYS2)
This Node.js script automates the generation of .lib files from .dll files for various libraries. It requires MSYS2 to be installed and configured.
```javascript
var dir='c:/msys64/mingw64'
var printdir='/c/msys64/mingw64'
function findandmakelibscommands(libnames)
{
var libs=libnames.split("|")
var re=new RegExp( "^(lib|")("+libs.join('|')+")[\d\b\-\.]+dll$" );
var dlls=require('fs').readdirSync(dir+'/bin').filter(function(a){ return a.match(re)})
var lines=dlls.map(function(file){
var dllfile=printdir+'/bin/'+file;
var libfile=printdir+'/lib/'+file.replace(/dll$/,'lib');
var deffile=file.replace(/dll$/,'def');
return 'gendef '+dllfile+'\r\n'+
'dlltool -d '+deffile+' -l '+libfile+' \r\n'+
'rm '+deffile+'\r\n'
}).join('\r\n')
var newlibs=dlls.map(function(file){
return " '-l<(GTK_Root)/lib/"+file.replace(/dll$/,'lib')+"'"
}).join(',\r\n')
console.log('\r\n'+lines+'\r\n\r\n new lib lines: \r\n'+newlibs+'\r\n\r\n')
}
findandmakelibscommands("cairo|png|pangocairo|pango|freetype|glib|gobject") // canvas
findandmakelibscommands("rsvg|gio|gdk_pixbuf|intl") // rsvg
```
--------------------------------
### Rebuild node-canvas from Source
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
Recompile node-canvas from source, typically after installing or updating dependencies.
```shell
node-gyp rebuild
```
--------------------------------
### Configure Heroku Buildpack for node-canvas
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Heroku
Set the Heroku buildpack to use heroku-buildpack-multi and specify the Cairo and Node.js buildpacks. This is necessary for installing Cairo and other dependencies required by node-canvas.
```bash
heroku config:add BUILDPACK_URL=https://github.com/mojodna/heroku-buildpack-multi.git#build-env
cat << EOF > .buildpacks
https://github.com/mojodna/heroku-buildpack-cairo.git
https://github.com/heroku/heroku-buildpack-nodejs.git
EOF
npm install --save canvas
git add .buildpacks package.json
git commit -m "node-canvas on Heroku"
git push heroku master
```
--------------------------------
### Convert Canvas to Buffer (Various Formats)
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Use `toBuffer()` to get raw or encoded image data. Supports PNG, JPEG, and raw BGRA formats. Options can control compression, quality, and filters.
```javascript
const buf = canvas.toBuffer()
```
```javascript
const buf2 = canvas.toBuffer('image/png', { compressionLevel: 3, filters: canvas.PNG_FILTER_NONE })
```
```javascript
const buf3 = canvas.toBuffer('image/jpeg', { quality: 0.5 })
```
```javascript
canvas.toBuffer((err, buf) => {
if (err) throw err // encoding failed
// buf is PNG-encoded image
})
```
```javascript
canvas.toBuffer((err, buf) => {
if (err) throw err // encoding failed
// buf is JPEG-encoded image at 95% quality
}, 'image/jpeg', { quality: 0.95 })
```
```javascript
const buf4 = canvas.toBuffer('raw')
const { stride, width } = canvas
// In memory, this is `canvas.height * canvas.stride` bytes long.
// The top row of pixels, in BGRA order on little-endian hardware,
// left-to-right, is:
const topPixelsBGRALeftToRight = buf4.slice(0, width * 4)
// And the third row is:
const row3 = buf4.slice(2 * stride, 2 * stride + width * 4)
```
```javascript
const myCanvas = createCanvas(w, h, 'pdf')
myCanvas.toBuffer() // returns a buffer containing a PDF-encoded canvas
```
```javascript
myCanvas.toBuffer('application/pdf', {
title: 'my picture',
keywords: 'node.js demo cairo',
creationDate: new Date()
})
```
--------------------------------
### registerFont
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Registers a font file with Canvas, allowing its use even if not installed as a system font.
```APIDOC
## registerFont()
### Description
To use a font file that is not installed as a system font, use `registerFont()` to register the font with Canvas.
### Signature
```ts
registerFont(path: string, { family: string, weight?: string, style?: string }) => void
```
### Parameters
- `path` (string): The file path to the font file.
- `options` (object): An object with font properties.
- `family` (string): The font family name. Required.
- `weight` (string): The font weight (e.g., 'normal', 'bold'). Optional, defaults to 'normal'.
- `style` (string): The font style (e.g., 'normal', 'italic'). Optional, defaults to 'normal'.
### Usage Example
```js
const { registerFont, createCanvas } = require('canvas')
registerFont('comicsans.ttf', { family: 'Comic Sans' })
const canvas = createCanvas(500, 500)
const ctx = canvas.getContext('2d')
ctx.font = '12px "Comic Sans"'
ctx.fillText('Everyone hates this font :(', 250, 10)
```
```
--------------------------------
### Set RPATH for Newer libcairo Versions in Node-Canvas
Source: https://github.com/automattic/node-canvas/wiki/Installation:-AWS-Lambda
Configures the linker flags (LDFLAGS) during npm install to set the RPATH for the built canvas.node binary. This ensures that the custom-built libcairo and libpixman libraries located in '/var/task/lib' are used by the Lambda function, overriding system defaults.
```bash
export LDFLAGS=-Wl,-rpath=/var/task/lib
npm install canvas@next
```
--------------------------------
### AWS Lambda Handler Function using Node-Canvas
Source: https://github.com/automattic/node-canvas/wiki/Installation:-AWS-Lambda
A sample Node.js handler function for AWS Lambda that utilizes the node-canvas library to create an image. It demonstrates basic canvas operations like creating a canvas, getting a 2D context, drawing text, and returning the image as a data URL.
```javascript
let
{createCanvas} = require("canvas");
function hello(event, context, callback) {
let
canvas = createCanvas(200, 200),
ctx = canvas.getContext('2d');
// Write "Awesome!"
ctx.font = '30px Impact';
ctx.rotate(0.1);
ctx.fillText('Awesome!', 50, 100);
// Draw line under text
let
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();
callback(null, '
');
}
module.exports = {hello};
```
--------------------------------
### Configure pkg-config with Internal GLib
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
If pkg-config configuration fails due to missing GLib, use this command to configure with the bundled copy.
```shell
./configure --with-internal-glib && make install
```
--------------------------------
### Generate Import Libraries for DLLs
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Windows-(using-MSYS2)
This sequence of commands generates .lib files from DLLs, which are necessary for the Visual Studio linker. It involves entering a MinGW64 shell, using gendef to create definition files, and then using dlltool to create the import libraries.
```bash
/mingw64_shell.bat # gives you a MinGW64 shell
gendef /mingw64/bin/libcairo-2.dll
dlltool -d libcairo-2.def -l /mingw64/lib/libcairo-2.lib
gendef /mingw64/bin/libpng16-16.dll
dlltool -d libpng16-16.def -l /mingw64/lib/libpng16-16.lib
rm libcairo-2.def libpng16-16.def
```
--------------------------------
### Create PDF Canvas
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Initializes a canvas for PDF output. The 'pdf' type must be specified during canvas creation.
```javascript
const canvas = createCanvas(200, 500, 'pdf')
```
--------------------------------
### Configure PNG Output for Canvas toBuffer
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
When converting to `image/png`, an optional config object can specify ZLIB compression level (0-9), filters, palette, background index, and resolution in pixels per meter. Resolution defaults to undefined.
```javascript
{compressionLevel: 6, filters: canvas.PNG_ALL_FILTERS, palette: undefined, backgroundIndex: 0, resolution: undefined}
```
--------------------------------
### MSYS2 Commands for RSVG Dependencies
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Windows-(using-MSYS2)
This output shows the commands generated by the Node.js script to create .lib files for RSVG dependencies. It includes steps to generate definition files, create .lib files using dlltool, and clean up temporary files.
```bash
> findandmakelibscommands("rsvg|gio|gdk_pixbuf|intl") // rsvg
gendef /c/msys64/mingw64/bin/libgdk_pixbuf-2.0-0.dll
dlltool -d libgdk_pixbuf-2.0-0.def -l /c/msys64/mingw64/lib/libgdk_pixbuf-2.0-0.lib
rm libgdk_pixbuf-2.0-0.def
gendef /c/msys64/mingw64/bin/libgio-2.0-0.dll
dlltool -d libgio-2.0-0.def -l /c/msys64/mingw64/lib/libgio-2.0-0.lib
rm libgio-2.0-0.def
gendef /c/msys64/mingw64/bin/libintl-8.dll
dlltool -d libintl-8.def -l /c/msys64/mingw64/lib/libintl-8.lib
rm libintl-8.def
gendef /c/msys64/mingw64/bin/librsvg-2-2.dll
dlltool -d librsvg-2-2.def -l /c/msys64/mingw64/lib/librsvg-2-2.lib
rm librsvg-2-2.def
new lib lines:
'-l<(GTK_Root)/lib/libgdk_pixbuf-2.0-0.lib',
'-l<(GTK_Root)/lib/libgio-2.0-0.lib',
'-l<(GTK_Root)/lib/libintl-8.lib',
'-l<(GTK_Root)/lib/librsvg-2-2.lib'
```
--------------------------------
### Convert Canvas to Data URL
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Use `toDataURL()` to get a base64-encoded data URL of the canvas content. Supports PNG and JPEG formats with optional quality settings.
```javascript
dataUrl = canvas.toDataURL() // defaults to PNG
```
```javascript
dataUrl = canvas.toDataURL('image/png')
```
```javascript
dataUrl = canvas.toDataURL('image/jpeg')
```
```javascript
dataUrl = canvas.toDataURL('image/jpeg', quality) // quality from 0 to 1
```
```javascript
canvas.toDataURL((err, png) => { }) // defaults to PNG
```
```javascript
canvas.toDataURL('image/png', (err, png) => { })
```
```javascript
canvas.toDataURL('image/jpeg', (err, jpeg) => { }) // sync JPEG is not supported
```
```javascript
canvas.toDataURL('image/jpeg', {...opts}, (err, jpeg) => { }) // see Canvas#createJPEGStream for valid options
```
```javascript
canvas.toDataURL('image/jpeg', quality, (err, jpeg) => { }) // spec-following; quality from 0 to 1
```
--------------------------------
### Configure PDF Output for Canvas toBuffer
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
When converting to `application/pdf`, an optional config object can specify document metadata such as title, author, subject, keywords, creator, creationDate, and modDate. Metadata requires Cairo 1.16.0 or later. Keywords should use spaces as separators.
```javascript
{title: string, author: string, subject: string, keywords: string, creator: string, creationDate: Date, modDate: Date}
```
--------------------------------
### Load Image with loadImage()
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Convenience method for loading images from URLs. It returns a Promise that resolves with the Image object. Always use .then() and .catch() or async/await for handling image loading.
```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)
})
```
```javascript
const myimg = await loadImage('http://server.com/image.png')
// do something with image
```
--------------------------------
### Render SVG Image to Canvas
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Use this snippet to draw an SVG image onto the canvas context. Ensure librsvg is installed for this functionality. The SVG is rasterized, not preserved as vector data.
```js
const img = new Image()
img.onload = () => ctx.drawImage(img, 0, 0)
img.onerror = err => { throw err }
img.src = './example.svg'
```
--------------------------------
### MSYS2 Commands for Canvas Dependencies
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Windows-(using-MSYS2)
This output shows the commands generated by the Node.js script to create .lib files for canvas dependencies. It includes steps to generate definition files, create .lib files using dlltool, and clean up temporary files.
```bash
> findandmakelibscommands("cairo|png|pangocairo|pango|freetype|glib|gobject") // canvas
gendef /c/msys64/mingw64/bin/libcairo-2.dll
dlltool -d libcairo-2.def -l /c/msys64/mingw64/lib/libcairo-2.lib
rm libcairo-2.def
gendef /c/msys64/mingw64/bin/libfreetype-6.dll
dlltool -d libfreetype-6.def -l /c/msys64/mingw64/lib/libfreetype-6.lib
rm libfreetype-6.def
gendef /c/msys64/mingw64/bin/libglib-2.0-0.dll
dlltool -d libglib-2.0-0.def -l /c/msys64/mingw64/lib/libglib-2.0-0.lib
rm libglib-2.0-0.def
gendef /c/msys64/mingw64/bin/libgobject-2.0-0.dll
dlltool -d libgobject-2.0-0.def -l /c/msys64/mingw64/lib/libgobject-2.0-0.lib
rm libgobject-2.0-0.def
gendef /c/msys64/mingw64/bin/libpango-1.0-0.dll
dlltool -d libpango-1.0-0.def -l /c/msys64/mingw64/lib/libpango-1.0-0.lib
rm libpango-1.0-0.def
gendef /c/msys64/mingw64/bin/libpangocairo-1.0-0.dll
dlltool -d libpangocairo-1.0-0.def -l /c/msys64/mingw64/lib/libpangocairo-1.0-0.lib
rm libpangocairo-1.0-0.def
gendef /c/msys64/mingw64/bin/libpng16-16.dll
dlltool -d libpng16-16.def -l /c/msys64/mingw64/lib/libpng16-16.lib
rm libpng16-16.def
new lib lines:
'-l<(GTK_Root)/lib/libcairo-2.lib',
'-l<(GTK_Root)/lib/libfreetype-6.lib',
'-l<(GTK_Root)/lib/libglib-2.0-0.lib',
'-l<(GTK_Root)/lib/libgobject-2.0-0.lib',
'-l<(GTK_Root)/lib/libpango-1.0-0.lib',
'-l<(GTK_Root)/lib/libpangocairo-1.0-0.lib',
'-l<(GTK_Root)/lib/libpng16-16.lib'
```
--------------------------------
### Copy System Libraries to Lambda Function Directory
Source: https://github.com/automattic/node-canvas/wiki/Installation:-AWS-Lambda
Copies essential shared libraries (like libcairo, libpng, libjpeg) from the system's /usr/lib64 directory into a local 'lib/' subdirectory. These libraries are required by node-canvas and must be bundled with the Lambda function.
```bash
mkdir lib
cp /usr/lib64/{libpng12.so.0,libjpeg.so.62,libpixman-1.so.0,libfreetype.so.6,\libcairo.so.2,libpango-1.0.so.0,libpangocairo-1.0.so.0,libpangoft2-1.0.so.0} lib/
```
--------------------------------
### Configure JPEG Output for Canvas toBuffer
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
When converting to `image/jpeg`, an optional config object can specify quality (0-1), progressive compression, and chroma subsampling. All properties are optional.
```javascript
{quality: 0.75, progressive: false, chromaSubsampling: true}
```
--------------------------------
### Create SVG Canvas
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Initializes a canvas for SVG output. The 'svg' type must be specified during canvas creation.
```javascript
const canvas = createCanvas(200, 500, 'svg')
```
--------------------------------
### Serverless Framework Configuration for Node-Canvas Lambda
Source: https://github.com/automattic/node-canvas/wiki/Installation:-AWS-Lambda
A basic serverless.yml configuration file for deploying the Node-Canvas Lambda function using the Serverless Framework. It specifies the AWS provider, runtime, and function handler.
```yaml
service: canvas-test
provider:
name: aws
runtime: nodejs6.10
stage: dev
region: us-east-1
memorySize: 128
timeout: 10
functions:
hello:
handler: index.hello
```
--------------------------------
### Create PDF Stream
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Returns a ReadableStream that emits the PDF content. Useful for piping PDF data directly.
```javascript
canvas.createPDFStream() // returns a ReadableStream that emits a PDF
```
--------------------------------
### PDF Output Support
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Enables PDF document creation by setting the canvas type to 'pdf'. Supports multi-page documents and metadata.
```APIDOC
## PDF Output Support
### Creating a PDF Canvas
```js
const { createCanvas } = require('canvas')
const canvas = createCanvas(200, 500, 'pdf')
const ctx = canvas.getContext('2d')
```
### Adding Pages
```js
ctx.addPage()
// Add content to the new page
ctx.addPage(width, height) // Add page with custom dimensions
```
### Generating PDF Output
```js
canvas.toBuffer() // Returns a PDF file buffer
canvas.createPDFStream() // Returns a ReadableStream for PDF
// With metadata (requires Cairo 1.16.0+)
canvas.toBuffer('application/pdf', {
title: 'my picture',
keywords: 'node.js demo cairo',
creationDate: new Date()
})
```
### Adding Hyperlinks and Tags
```js
ctx.beginTag('Link', "uri='https://google.com'")
ctx.fillText('Hello World', 50, 80)
ctx.endTag('Link')
ctx.beginTag('Link', "uri='https://google.com' rect=[50 80 100 20]")
ctx.endTag('Link')
// For accessibility and structure, use tags like 'P', 'H1', 'TABLE'
```
```
--------------------------------
### Convert Canvas to Buffer Directly
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Creates and returns a Buffer object representing the canvas image. Specify mimeType and configuration options for formats like JPEG or PNG. For JPEG, configure quality, progressive compression, and chroma subsampling. For PNG, configure compression level, filters, palette, and resolution.
```javascript
canvas.toBuffer(mimeType, config)
```
--------------------------------
### Convert Canvas to Buffer with Callback
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Creates a Buffer object from the canvas content. If a callback is provided, the buffer is passed to it. Not supported for `raw` mimeType or PDF/SVG canvases. Ensure correct mimeType and config for desired output format.
```javascript
canvas.toBuffer((err, result) => {}, mimeType, config)
```
--------------------------------
### Create ImageData Instance
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Creates an ImageData instance from raw pixel data or dimensions. This method is compatible with 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)
```
--------------------------------
### SVG Output Support
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Enables SVG document creation by setting the canvas type to 'svg'.
```APIDOC
## SVG Output Support
### Creating an SVG Canvas
```js
const { createCanvas } = require('canvas')
const canvas = createCanvas(200, 500, 'svg')
const ctx = canvas.getContext('2d')
```
### Generating SVG Output
```js
const fs = require('fs')
fs.writeFileSync('out.svg', canvas.toBuffer())
```
```
--------------------------------
### Set Experimental Pixel Format
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Configure the canvas context with an experimental pixel format, such as 'A8'. The default format is 'RGBA32'. This can be useful for grayscale images or indexed PNGs.
```js
const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d', { pixelFormat: 'A8' })
```
--------------------------------
### Set PKG_CONFIG_PATH for Cairo
Source: https://github.com/automattic/node-canvas/wiki/Installation:-Mac-OS-X
If Cairo is not found by pkg-config, set the PKG_CONFIG_PATH environment variable to include the local pkgconfig directory.
```shell
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
```
--------------------------------
### createCanvas
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Creates a Canvas instance. This method is compatible with both Node.js and web browsers.
```APIDOC
## createCanvas()
### Description
Creates a Canvas instance. This method works in both Node.js and Web browsers, where there is no Canvas constructor.
### Signature
```ts
createCanvas(width: number, height: number, type?: 'PDF'|'SVG') => Canvas
```
### Usage Example
```js
const { createCanvas } = require('canvas')
const mycanvas = createCanvas(200, 200)
const myPDFcanvas = createCanvas(600, 800, 'pdf')
```
```
--------------------------------
### Create Canvas Instance
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Use createCanvas to create a new Canvas instance. It supports specifying dimensions and an optional type for PDF or SVG output.
```javascript
const { createCanvas } = require('canvas')
const mycanvas = createCanvas(200, 200)
const myPDFcanvas = createCanvas(600, 800, 'pdf') // see "PDF Support" section
```
--------------------------------
### Canvas#createPNGStream()
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Creates a ReadableStream that emits PNG-encoded data from the canvas. Supports configuration for compression and filters.
```APIDOC
## Canvas#createPNGStream()
### Description
Creates a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_class_stream_readable) that emits PNG-encoded data.
### Method
`canvas.createPNGStream(config?: any) => ReadableStream`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters for `config`
* `config` (object, optional): 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`: number (0-9)
* `filters`: number (e.g., `canvas.PNG_ALL_FILTERS`)
* `palette`: Uint8ClampedArray (for indexed PNGs)
* `backgroundIndex`: number (for indexed PNGs, defaults to 0)
* `resolution`: any (optional)
### Request Example
```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'`:
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
})
```
### Response
#### Success Response (ReadableStream)
Returns a `ReadableStream` that emits PNG-encoded data.
#### Response Example
```javascript
// The stream can be piped to a file or another destination.
// stream.pipe(process.stdout);
```
```
--------------------------------
### Canvas#toBuffer()
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Converts the canvas content to a Buffer in various image formats. Supports PNG, JPEG, and raw pixel data. Asynchronous versions are also available.
```APIDOC
## Canvas#toBuffer()
### Description
Converts the canvas content to a Buffer in various image formats.
### Method
`canvas.toBuffer(type?, options?)
canvas.toBuffer(callback)
canvas.toBuffer(type?, options?, callback)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters for `toBuffer(type?, options?)`
* `type` (string, optional): The MIME type of the image (e.g., 'image/png', 'image/jpeg'). Defaults to 'image/png'.
* `options` (object, optional): Configuration options for encoding.
* For PNG: `{ compressionLevel: number, filters: number }`
* For JPEG: `{ quality: number }`
### Parameters for `toBuffer(callback)`
* `callback` (function): A callback function that receives an error and the buffer.
### Parameters for `toBuffer(type?, options?, callback)`
* `type` (string, optional): The MIME type of the image.
* `options` (object, optional): Configuration options for encoding.
* `callback` (function): A callback function that receives an error and the buffer.
### Request Example
```js
// Default: buf contains a PNG-encoded image
const buf = canvas.toBuffer()
// PNG-encoded, zlib compression level 3 for faster compression but bigger files, no filtering
const buf2 = canvas.toBuffer('image/png', { compressionLevel: 3, filters: canvas.PNG_FILTER_NONE })
// JPEG-encoded, 50% quality
const buf3 = canvas.toBuffer('image/jpeg', { quality: 0.5 })
// BGRA pixel values, native-endian
const buf4 = canvas.toBuffer('raw')
const { stride, width } = canvas
// In memory, this is `canvas.height * canvas.stride` bytes long.
// The top row of pixels, in BGRA order on little-endian hardware, left-to-right, is:
const topPixelsBGRALeftToRight = buf4.slice(0, width * 4)
// And the third row is:
const row3 = buf4.slice(2 * stride, 2 * stride + width * 4)
// SVG and PDF canvases
const myCanvas = createCanvas(w, h, 'pdf')
myCanvas.toBuffer() // returns a buffer containing a PDF-encoded canvas
// With optional metadata:
myCanvas.toBuffer('application/pdf', {
title: 'my picture',
keywords: 'node.js demo cairo',
creationDate: new Date()
})
```
### Response
#### Success Response (Buffer)
Returns a Buffer containing the encoded image data.
#### Response Example
```js
// Example for PNG buffer
//
```
### Asynchronous Usage
```js
canvas.toBuffer((err, buf) => {
if (err) throw err // encoding failed
// buf is PNG-encoded image
})
canvas.toBuffer((err, buf) => {
if (err) throw err // encoding failed
// buf is JPEG-encoded image at 95% quality
}, 'image/jpeg', { quality: 0.95 })
```
```
--------------------------------
### loadImage
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
A convenience method for loading images, compatible with both Node.js and web browsers.
```APIDOC
## loadImage()
### Description
Convenience method for loading images. This method works in both Node.js and Web browsers.
### Signature
```ts
loadImage() => Promise
```
### Usage Example
```js
const { loadImage } = require('canvas')
// Using Promises
loadImage('http://server.com/image.png').then(myimg => {
// do something with image
}).catch(err => {
console.log('oh no!', err)
})
// Using async/await
const myimg = await loadImage('http://server.com/image.png')
// do something with image
```
```
--------------------------------
### Create PNG Stream from Canvas
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Use `createPNGStream()` to generate a readable stream of PNG-encoded image data. Supports ZLIB compression and filter options.
```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.'))
```
```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
})
```
--------------------------------
### Set Anti-aliasing Mode
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Configures the anti-aliasing method for rendering. Options include 'default', 'none', 'gray', and 'subpixel'.
```typescript
context.antialias: 'default'|'none'|'gray'|'subpixel'
```
--------------------------------
### Write to Framebuffer Device with node-canvas
Source: https://github.com/automattic/node-canvas/wiki/Using-with-framebuffer-devices
Use this snippet to draw on a canvas and then write the raw buffer to a framebuffer device. Ensure the pixel format is set to RGB16_565 for compatibility with many framebuffer devices. The output buffer size should match the expected width * height * 2 bytes.
```javascript
const {createCanvas} = require("canvas");
const canvas = createCanvas(480, 320);
// Draw to your canvas:
const ctx = canvas.getContext("2d", {pixelFormat: "RGB16_565"}); // important: RGB16_565
ctx.font = "30px impact";
ctx.fillStyle = "red";
ctx.fillText("Hello!", 50, 100);
// Write to the framebuffer device:
const fs = require("fs");
const fb = fs.openSync("/dev/fb1", "w"); // where /dev/fb1 is the path to your fb device
const buff = canvas.toBuffer("raw");
console.log(buff.byteLength); // should be equal to width*height*2
fs.writeSync(fb, buff, 0, buff.byteLength, 0);
```
--------------------------------
### createImageData
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Creates an ImageData instance. This method is compatible with both Node.js and web browsers.
```APIDOC
## createImageData()
### Description
Creates an ImageData instance. This method works in both Node.js and Web browsers.
### Signature
```ts
createImageData(width: number, height: number) => ImageData
createImageData(data: Uint8ClampedArray, width: number, height?: number) => ImageData
createImageData(data: Uint16Array, width: number, height?: number) => ImageData
```
### Usage Example
```js
const { createImageData } = require('canvas')
const width = 20, height = 20
const arraySize = width * height * 4
const mydata = createImageData(new Uint8ClampedArray(arraySize), width)
```
```
--------------------------------
### Canvas#toBuffer()
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Converts the canvas content into a Buffer object in a specified image format. Supports various mime types including PNG, JPEG, raw, PDF, and SVG, with configurable options for each format.
```APIDOC
## Canvas#toBuffer()
### Description
Creates a [`Buffer`](https://nodejs.org/api/buffer.html) object representing the image contained in the canvas.
### Method Signatures
1. `canvas.toBuffer((err: Error|null, result: Buffer) => void, mimeType?: string, config?: any) => void`
2. `canvas.toBuffer(mimeType?: string, config?: any) => Buffer`
### Parameters
* **callback** (function) - Optional. 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** (string) - Optional. A string indicating the image format. Valid options are `image/png`, `image/jpeg` (if node-canvas was built with JPEG support), `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** (object) - Optional. Configuration options specific to the `mimeType`.
* For `image/jpeg`: `{quality: 0.75, progressive: false, chromaSubsampling: true}`. All properties are optional.
* For `image/png`: `{compressionLevel: 6, filters: canvas.PNG_ALL_FILTERS, palette: undefined, backgroundIndex: 0, resolution: undefined}`. All properties are optional.
* For `application/pdf`: `{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. *Adding metadata requires Cairo 1.16.0 or later.*
### Return Value
* If no callback is provided, a [`Buffer`](https://nodejs.org/api/buffer.html).
* If a callback is provided, none.
```
--------------------------------
### CanvasRenderingContext2D#patternQuality
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Sets the rendering quality for patterns (gradients, images, etc.). Accepts 'fast', 'good', 'best', 'nearest', or 'bilinear'. Defaults to 'good'.
```APIDOC
## CanvasRenderingContext2D#patternQuality
### Description
Sets the rendering quality for patterns (gradients, images, etc.).
### Type
`'fast'|'good'|'best'|'nearest'|'bilinear'`
### Default
`'good'`
```
--------------------------------
### Image#src
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Sets the source of an Image object. Supports various input types including data URIs, remote URLs, local file paths, and Buffers.
```APIDOC
## Image#src
### Description
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.
### Signature
```ts
img.src: string|Buffer
```
### Usage Example
```javascript
const { Image } = require('canvas')
// From a buffer:
fs.readFile('images/squid.png', (err, squid) => {
if (err) throw err
const img = new Image()
img.onload = () => ctx.drawImage(img, 0, 0)
img.onerror = err => { throw err }
img.src = squid
})
// From a local file path:
const img = new Image()
img.onload = () => ctx.drawImage(img, 0, 0)
img.onerror = err => { throw err }
img.src = 'images/squid.png'
// From a remote URL:
img.src = 'http://picsum.photos/200/300'
// ... as above
// From a `data:` URI:
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
// ... as above
/*
* 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.
*/
```
```
--------------------------------
### Canvas#toDataURL()
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Converts the canvas content to a Data URL string in various image formats. Supports PNG and JPEG with optional quality settings. Asynchronous versions are also available.
```APIDOC
## Canvas#toDataURL()
### Description
Converts the canvas content to a Data URL string. Supports PNG and JPEG formats, with options for quality and asynchronous execution.
### Method
`canvas.toDataURL(type?, options?, callback?)
canvas.toDataURL(type?, quality?, callback?)
canvas.toDataURL(type?, callback?)
canvas.toDataURL(callback?)
`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* `type` (string, optional): The MIME type of the image (e.g., 'image/png', 'image/jpeg'). Defaults to 'image/png'.
* `options` (object, optional): Configuration options for JPEG encoding (e.g., `{ quality: number }`). See `Canvas#createJPEGStream` for valid options.
* `quality` (number, optional): The quality of the JPEG image (0 to 1). Used when `type` is 'image/jpeg'.
* `callback` (function, optional): A callback function that receives an error and the Data URL string.
### Request Example
```js
dataUrl = canvas.toDataURL() // defaults to PNG
dataUrl = canvas.toDataURL('image/png')
dataUrl = canvas.toDataURL('image/jpeg')
dataUrl = canvas.toDataURL('image/jpeg', quality) // quality from 0 to 1
```
### Response
#### Success Response (string)
Returns a Data URL string representing the canvas content.
#### Response Example
```javascript
// Example for a PNG Data URL
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
```
### Asynchronous Usage
```js
canvas.toDataURL((err, png) => { })
canvas.toDataURL('image/png', (err, png) => { })
canvas.toDataURL('image/jpeg', (err, jpeg) => { })
canvas.toDataURL('image/jpeg', {...opts}, (err, jpeg) => { })
canvas.toDataURL('image/jpeg', quality, (err, jpeg) => { })
```
### Note
*Sync JPEG is not supported. For JPEG, use the asynchronous callback or stream methods.*
```
--------------------------------
### CanvasRenderingContext2D#globalCompositeOperation
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Sets the global composite operation. Supports standard operations plus 'saturate'.
```APIDOC
## CanvasRenderingContext2D#globalCompositeOperation
### Description
Sets the global composite operation.
### Supported Operations
Standard composite operations plus `'saturate'`.
```
--------------------------------
### CanvasRenderingContext2D#quality
Source: https://github.com/automattic/node-canvas/blob/master/Readme.md
Sets the rendering quality for transformations affecting more than just patterns. Accepts 'fast', 'good', 'best', 'nearest', or 'bilinear'. Defaults to 'good'.
```APIDOC
## CanvasRenderingContext2D#quality
### Description
Sets the rendering quality for transformations affecting more than just patterns.
### Type
`'fast'|'good'|'best'|'nearest'|'bilinear'`
### Default
`'good'`
```