node-canvas

repository·master·Indexed 27 days ago

https://github.com/automattic/node-canvas

A Cairo-backed Canvas implementation for Node.js that provides a web-standard Canvas API for server-side image manipulation and generation. It supports creating image, PDF, and SVG documents, loading images via loadImage(), and registering custom fonts. The library includes support for various pixel formats and provides methods to export content as Buffers, data URLs, or streams.

Tokens
5.5K
Snippets
16
Records
31
Agent score
95%

What's inside node-canvas

  1. Render SVG images to canvas

    master

    If librsvg is installed, you can render SVG images onto a canvas context by loading them as an Image object. Note that this process rasterizes the SVG; it does not preserve the original SVG vector data.

    const img = new Image()
    img.onload = () => ctx.drawImage(img, 0, 0)
    img.onerror = err => { throw err }
    img.src = './example.svg'
  2. Install node-canvas via npm

    master

    Install the canvas package using npm. By default, pre-built binaries are downloaded for the following platforms:

    • macOS x86/64
    • macOS aarch64 (Apple silicon)
    • Linux x86/64 (glibc only)
    • Windows x86/64

    Requirements:

    • Minimum Node.js version: 18.12.0

    If you need to build from source, use the --build-from-source flag.

    $ npm install canvas
  3. Run tests

    master

    To run tests, ensure you have built the latest version and installed dependencies using --build-from-source.

    • Unit tests: npm run test
    • Visual tests: Run npm run test-server and view the results in a browser at http://localhost:4000.
    npm install --build-from-source
    npm run test
    npm run test-server
  4. Create SVG documents

    master

    To generate SVG documents, specify 'svg' as the type when calling createCanvas(). You can then use standard canvas primitives and export the result using .toBuffer().

    const canvas = createCanvas(200, 500, 'svg')
    // Use the normal primitives.
    fs.writeFileSync('out.svg', canvas.toBuffer())
  5. Create PDF documents

    master

    You can generate PDF documents by specifying 'pdf' as the type when calling createCanvas().

    To create multi-page PDFs, use the .addPage() method. You can also specify different dimensions for subsequent pages by passing width and height to .addPage().

    To add hyperlinks, use .beginTag('Link', "uri='URL'" ) and .endTag('Link'). You can also define a specific clickable rectangle using the rect attribute within the tag string.

    To export the PDF, use .toBuffer() or .createPDFStream().

  6. Compile node-canvas from source

    master

    If you are on an unsupported OS/architecture or use --build-from-source, you must compile the module. This requires Cairo (v1.10.0+) and Pango. Optional dependencies include libgif/giflib (for GIF), librsvg (for SVG), and libjpeg (for JPEG).

    OS-specific installation commands:

    OSCommand
    macOSbrew install pkg-config cairo pango libpng jpeg giflib librsvg pixman python-setuptools
    Ubuntusudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev
    Fedorasudo yum install gcc-c++ cairo-devel pango-devel libjpeg-turbo-devel giflib-devel
    Solarispkgin install cairo pango pkg-config xproto renderproto kbproto xextproto
    OpenBSDdoas pkg_add cairo pango png jpeg giflib
    WindowsSee the wiki
    OthersSee the wiki

    Troubleshooting macOS: If you encounter issues on macOS v10.11+, run: xcode-select --install.

  7. Quick Example: Drawing on a canvas

    master

    This example demonstrates how to create a canvas, get a 2D context, draw text with rotation, draw a line, and overlay a loaded image.

    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('<img src="' + canvas.toDataURL() + '" />')
    })
  8. Unregister all fonts with deregisterAllFonts()

    master

    Use deregisterAllFonts() to remove all previously registered fonts. This is particularly useful for cleaning up the environment during testing.

    const { registerFont, createCanvas, deregisterAllFonts } = require('canvas')
    
    describe('text rendering', () => {
        afterEach(() => {
            deregisterAllFonts();
        })
        it('should render text with Comic Sans', () => {
            registerFont('comicsans.ttf', { family: 'Comic Sans' })
    
            const canvas = createCanvas(500, 500)
            const ctx = canvas.getContext('2d')
            
            ctx.font = '12px "Comic Sans"'
            ctx.fillText('Everyone loves this font :)', 250, 10)
            
            // assertScreenshot()
        })
    })
  9. Load images with loadImage()

    master

    The loadImage() method is a convenience function that returns a Promise<Image>. It can load images from URLs, local file paths, or data: URIs. Always use .then()/.catch() or async/await to handle the asynchronous loading process.

    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
  10. Create a Canvas instance with createCanvas()

    master

    Use createCanvas(width, height, [type]) to create a new Canvas instance. The type parameter allows you to specify 'PDF' or 'SVG' for non-image canvases. This method is compatible with both Node.js and web browsers.

    const { createCanvas } = require('canvas')
    const mycanvas = createCanvas(200, 200)
    const myPDFcanvas = createCanvas(600, 800, 'pdf') // see "PDF Support" section
  11. Configure text drawing mode with textDrawingMode

    master

    The context.textDrawingMode property determines how text is rendered. Options: 'path' (default) or 'glyph'.

    Behavior by Canvas Type:

    • Standard (image): Both modes rasterize text. 'glyph' is faster but may have lower quality when rotated/translated.
    • PDF: 'glyph' embeds text instead of paths. This is faster, results in smaller files, and makes text selectable. Recommended for PDF canvases.
    • SVG: 'glyph' uses <symbol> and <use> elements for efficiency. 'path' creates <path> elements for each string.