Created
August 21, 2019 06:12
-
-
Save wong2/23370b63c125b95e3f33e556ae9b1019 to your computer and use it in GitHub Desktop.
node canvas auto wrap text by max width
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 fillText(ctx, text, x, y, maxWidth, spacing = 0){ | |
const lines = text.split('\n') | |
let lineHeight = 0 | |
for (const line of lines) { | |
if (!line) { | |
y += lineHeight | |
continue | |
} | |
let s = '' | |
for (const char of line) { | |
const { width, height } = measureText(ctx, s + char) | |
if (width <= maxWidth) { | |
s += char | |
} else { | |
ctx.fillText(s, x, y) | |
lineHeight = height + spacing | |
y += lineHeight + spacing | |
s = char | |
} | |
} | |
if (s) { | |
const { height } = measureText(ctx, s) | |
ctx.fillText(s, x, y) | |
lineHeight = height + spacing | |
y += lineHeight | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment