Last active
June 8, 2018 08:16
-
-
Save lakinmohapatra/c0a09df37b3647b0930d99cbddce5615 to your computer and use it in GitHub Desktop.
Wrap text on canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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