Skip to content

Instantly share code, notes, and snippets.

@isbasex
Last active October 23, 2017 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isbasex/5a0f76f5a9bef37fa1be6b00037b20b4 to your computer and use it in GitHub Desktop.
Save isbasex/5a0f76f5a9bef37fa1be6b00037b20b4 to your computer and use it in GitHub Desktop.
Image Generator for node.js

Installation

$ yarn add canvas express

Unless previously installed you'll need Cairo and Pango. For system-specific installation view the Wiki.

Currently the minimum version of node required is 4.0.0

You can quickly install the dependencies by using the command for your OS:

OS Command
OS X brew install pkg-config cairo pango libpng jpeg giflib
Ubuntu sudo apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
Fedora sudo yum install cairo cairo-devel cairomm-devel libjpeg-turbo-devel pango pango-devel pangomm pangomm-devel giflib-devel
Solaris pkgin install cairo pango pkg-config xproto renderproto kbproto xextproto
Windows Instructions on our wiki

El Capitan users: If you have recently updated to El Capitan and are experiencing trouble when compiling, run the following command: xcode-select --install. Read more about the problem on Stack Overflow.

const express = require('express')
const app = express()
const { createCanvas } = require('canvas')
const SIZE = 1080
const DEFAULT_COLOR = '#e3e3e3'
app.get('*', (req, res) => {
const { h, w, c, text, fc } = req.query
const width = Number(w) || SIZE
const height = Number(h) || SIZE
const canvas = createCanvas(width, height)
const ctx = canvas.getContext('2d')
ctx.fillStyle = c || DEFAULT_COLOR
ctx.fillRect(0, 0, width, height)
ctx.fillStyle = fc || '#ca26ee'
ctx.font = `300px "Operator Mono"`
text && ctx.fillText(text, 0, 300)
ctx.textAlign = 'center'
res.setHeader('Content-Type', 'image/png')
res.send(canvas.toBuffer())
})
app.listen(3333, '0.0.0.0', () => {
console.log(`App listening on localhost:3333!`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment