Skip to content

Instantly share code, notes, and snippets.

@kylemcdonald
Created April 16, 2019 23:45
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 kylemcdonald/d9025977d87732b91c8fa0cd9a7fc9d3 to your computer and use it in GitHub Desktop.
Save kylemcdonald/d9025977d87732b91c8fa0cd9a7fc9d3 to your computer and use it in GitHub Desktop.
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