Skip to content

Instantly share code, notes, and snippets.

@bcks
Last active January 18, 2018 13:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcks/6f3c16ee0cec701c10ce67b104865517 to your computer and use it in GitHub Desktop.
Save bcks/6f3c16ee0cec701c10ce67b104865517 to your computer and use it in GitHub Desktop.
Make an image of text
// a node.js method for creating images of text
// as used in https://twitter.com/nytanon and https://twitter.com/wapoanon
function makeImage(object, que, callback) {
var text = object.text;
var Canvas = require('canvas'),
Image = Canvas.Image,
canvas = new Canvas(200, 200),
context = canvas.getContext('2d');
var fs = require('fs'),
out = fs.createWriteStream('/tmp/' + object.id + '.png'),
stream = canvas.pngStream();
stream.on('data', function(chunk) {
out.write(chunk);
});
stream.on('end', function() {
setTimeout(function() {
tweet(object, que, callback);
// and don't forget to delete the image from /tmp after you tweet.
}, 500);
});
context.font = '24px Georgia';
var maxWidth = 600;
var lineHeight = 30;
var xMargin = 10;
var x = xMargin;
var y = lineHeight;
var text = object.snippet;
var lines = 0;
var width = 0;
var height = lineHeight;
var words = text.split(' ');
var line = '';
// calculate
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
line = words[n] + ' ';
height += lineHeight;
lines++;
} else {
width = Math.max(width, testWidth);
line = testLine;
}
if (n + 1 == words.length) {
var words = text.split(' ');
x = xMargin;
y = lineHeight;
line = '';
// Calculate canvas size, add margin
context.canvas.width = xMargin * 2 + width;
context.canvas.height = height + xMargin;
context.fillStyle = "white";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
context.font = '24px Georgia';
context.fillStyle = "black";
// render
for (var i = 0; i < words.length; i++) {
rTestLine = line + words[i] + ' ';
var metrics = context.measureText(rTestLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && i > 0) {
context.fillText(line, x, y);
line = words[i] + ' ';
y += lineHeight;
} else {
line = rTestLine;
}
if (i + 1 == words.length) {
context.fillText(line, x, y);
}
}
}
}
canvas.pngStream();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment