Skip to content

Instantly share code, notes, and snippets.

@stevenkuipers
Created May 23, 2018 09:51
Show Gist options
  • Save stevenkuipers/da89ca29f649f4146630dd529cd9af9b to your computer and use it in GitHub Desktop.
Save stevenkuipers/da89ca29f649f4146630dd529cd9af9b to your computer and use it in GitHub Desktop.
A textwrapper for canvas text, specify a maximum width and it will break sentences into different lines.
// @Params Object - CanvasRenderingContext2D
// String
// Integer - X coordinate
// Integer - Y Coordinate
// Integer - Maxwidth of textBox
// Integer - Lineheight
// function will split words and add linebreaks if sentences are longer than specified max width,
// if sentence is rearranged it will return an object with the new line, x and y coordinates.
// @Returns Object
const wrapText = (ctx, text, x, y, maxWidth, lineHeight) => {
let words = text.split(' ');
let line = '';
for(let n = 0; n < words.length; n++) {
let baseLine = line + words[n] + ' ';
let metrics = ctx.measureText(baseLine);
let testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
ctx.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = baseLine;
}
}
return ({line : line, x : x, y : y});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment