Skip to content

Instantly share code, notes, and snippets.

@nkint
Created September 22, 2017 12:49
Show Gist options
  • Save nkint/c9c05d8a0de4d736f27036d594645fd0 to your computer and use it in GitHub Desktop.
Save nkint/c9c05d8a0de4d736f27036d594645fd0 to your computer and use it in GitHub Desktop.
Wrap text on canvas
export function wrapTextCanvas(context, text, x, y, maxWidth, lineHeight, drawFlag = true) {
const cars = text.split('\n')
for (let ii = 0; ii < cars.length; ii++) {
let line = ''
const words = cars[ii].split(' ')
for (let n = 0; n < words.length; n++) {
const testLine = line + words[n] + ' '
const metrics = context.measureText(testLine)
const testWidth = metrics.width
if (testWidth > maxWidth) {
if (drawFlag) {
context.fillText(line, x, y)
}
line = words[n] + ' '
y += lineHeight
} else {
line = testLine
}
}
if (drawFlag) {
context.fillText(line, x, y)
}
y += lineHeight
}
return y
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment