You can measure text to get the width of a sentence like this:
ctx.measureText('I am a sentence').width
You can do this because you set the font on the context directly to match whatever CSS-styled text in your HTML that you're trying to really measure.
ctx.font = '24px MyFont';
But what if I want to apply whitespace: pre
to the text? I seem to be getting weird results that don't measure up.
What I'm trying to do is simply calculate the words that can fit safely on a single line. That's it. But sometimes what I measure is smaller than what gets rendered, so I am starting to suspect that the canvas measurement technique isn't actually an accurate tool.
How do I accurately measure the width of a sentence taking into account all the features of the styling such as letter-spacing
, whitespace: pre
, etc.?