Skip to content

Instantly share code, notes, and snippets.

@mnmly
Last active January 4, 2016 06:39
Show Gist options
  • Save mnmly/8583502 to your computer and use it in GitHub Desktop.
Save mnmly/8583502 to your computer and use it in GitHub Desktop.
node-canvas + opentype.js demo.

node-canvas + opentype.js demo.

bold.png

regular.png

/**
* Module Dependencies
*/
var fs = require('fs');
var Canvas = require('canvas');
var OpenType = require('opentype.js');
/**
* Draw `hello` with typeface located at `typeface` then output .png with name `filename`
* when writing is done, `next` callback is triggered.
*
* @param {String} typepath
* @param {String} filename
* @param {Function} next
*/
function drawHello(typepath, filename, next){
OpenType.load(typepath, function(err, font){
var canvas = new Canvas(500, 500);
var ctx = canvas.getContext('2d');
var path = font.getPath('Hello, World!', 30, 150, 30);
path.draw(ctx);
var out = fs.createWriteStream('output/' + filename);
var stream = canvas.pngStream();
stream.on('data', function(chunk){
out.write(chunk);
});
stream.on('end', function(){
next();
});
});
}
drawHello(__dirname + '/assets/font/Montserrat-Bold.ttf', 'bold.png', function(){
console.log('done');
});
drawHello(__dirname + '/assets/font/Montserrat-Regular.ttf', 'regular.png', function(){
console.log('done');
});
{
"name": "node-canvas-opentype-demo",
"dependencies": {
"opentype.js": "git+https://github.com/nodebox/opentype.js.git",
"canvas": "~1.1.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment