Created
June 26, 2020 17:26
-
-
Save risingBirdSong/0fd7c8bf9b87d3b73c14a6e7923613dd to your computer and use it in GitHub Desktop.
canvas text helper function
This file contains hidden or 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
//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