Skip to content

Instantly share code, notes, and snippets.

@wong2
Created August 21, 2019 06:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wong2/23370b63c125b95e3f33e556ae9b1019 to your computer and use it in GitHub Desktop.
Save wong2/23370b63c125b95e3f33e556ae9b1019 to your computer and use it in GitHub Desktop.
node canvas auto wrap text by max width
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