Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save risingBirdSong/0fd7c8bf9b87d3b73c14a6e7923613dd to your computer and use it in GitHub Desktop.
Save risingBirdSong/0fd7c8bf9b87d3b73c14a6e7923613dd to your computer and use it in GitHub Desktop.
canvas text helper function
//https://www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(" ");
var line = "";
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) {
context.fillText(line, x, y);
line = words[n] + " ";
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment