Skip to content

Instantly share code, notes, and snippets.

@AlexBezuska
Created December 6, 2016 21:48
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 AlexBezuska/a0f0cfbad78a87293a407d4a42da27de to your computer and use it in GitHub Desktop.
Save AlexBezuska/a0f0cfbad78a87293a407d4a42da27de to your computer and use it in GitHub Desktop.
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(" ");
var line = "";
for (var i = 0; i < words.length; i++) {
var testLine = line + words[i] + " ";
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && i > 0) {
context.fillText(line, x, y);
line = words[i] + " ";
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