Created
September 22, 2017 12:49
-
-
Save nkint/c9c05d8a0de4d736f27036d594645fd0 to your computer and use it in GitHub Desktop.
Wrap text on canvas
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
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