javascriptnode.jsnode-canvas

NodeJs Canvas does not appear


I am installing node js canvas API using the following code:

npm install canvas --save

I have written code for displaying a canvas, but it doesn't show anything. The code doesn't show errors on executing:

const { createCanvas } = require('canvas')
const width = 1200
const height = 600

const canvas = createCanvas(width, height)
const context = canvas.getContext('2d')

context.fillStyle = '#fff'
context.fillRect(0, 0, width, height)

Solution

  • This package provides us a Node.js based implementation of the Canvas API that we know and love in the browser.

    Except instead of getting a Canvas instance from a <canvas> HTML element, We load the library, get the function createCanvas out of it.

    Example:

    const { createCanvas, loadImage } = require('canvas')
    const canvas = createCanvas(200, 200)
    const ctx = canvas.getContext('2d')
    
    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('./imgs.jpg').then((image) => {
      ctx.drawImage(image, 50, 0, 70, 70)
     
      console.log('<img src="' + canvas.toDataURL() + '" />')
    })