Skip to content

Instantly share code, notes, and snippets.

@mooyoul
Created December 27, 2017 08:52
Show Gist options
  • Save mooyoul/68584690a0239148231112a533af1c23 to your computer and use it in GitHub Desktop.
Save mooyoul/68584690a0239148231112a533af1c23 to your computer and use it in GitHub Desktop.
Render text using Canvas in Node.js environment
const Canvas = require('canvas');
const fs = require('fs');
const canvas = new Canvas(640, 480); // creates 6400px * 480px canvas
const ctx = canvas.getContext('2d'); // get 2d context
// Fill background
ctx.fillStyle = "rgb(255, 255, 255)"
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw Text
ctx.font = '72px "Apple SD Gothic Neo"'; // setup font
ctx.fillStyle = "#333";
ctx.rotate(0.2); // rotate text by (90deg * 0.1)
ctx.fillText('안녕하세요!', 200, 200); // write text at (50px, 100px) position
// Write to file
const bufImage = canvas.toBuffer(); // get buffer instance which contains image data, image format is PNG by default
fs.writeFileSync('rendered.png', bufImage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment