Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tile text across a canvas.
function tileText(text, canvas, config) {
var fontSize = config.fontSize || 20;
var lineHeight = config.lineHeight || 1.2;
var fontFamily = config.fontFamily || 'sans-serif';
var pad = config.padding || fontSize;
var lineHeightPx = lineHeight * fontSize;
if (config.lineSnap) {
var textRows = Math.floor(canvas.height / lineHeightPx);
lineHeightPx = canvas.height / textRows;
}
var x = -pad;
var y = (lineHeightPx - fontSize) / 2;
var w = canvas.width + 2 * pad;
var h = canvas.height + 2 * pad;
var cur = '';
var yoff = 0;
var ctx = canvas.getContext('2d');
ctx.save();
ctx.font = fontSize + 'px "' + fontFamily + '"';
ctx.textAlign = 'start';
ctx.textBaseline = 'top';
if (text[text.length - 1] != ' ') {
text += ' ';
}
var n = text.length;
var characters = 0;
var lines = 0;
while (yoff < h) {
cur += text[characters % n];
var textWidth = ctx.measureText(cur)['width'];
if (textWidth > w) { // && Math.random() < 0.5 // good place to add randomness
ctx.fillText(cur, x, y + yoff);
yoff += lineHeightPx;
cur = '';
lines++;
}
characters++;
}
ctx.restore();
return {
characters: characters,
lines: lines
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment