Skip to content

Instantly share code, notes, and snippets.

@lakinmohapatra
Last active June 8, 2018 08:16
Show Gist options
  • Save lakinmohapatra/c0a09df37b3647b0930d99cbddce5615 to your computer and use it in GitHub Desktop.
Save lakinmohapatra/c0a09df37b3647b0930d99cbddce5615 to your computer and use it in GitHub Desktop.
Wrap text on canvas
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) {
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