How can I set a maximal height for drawing text in an HTML5 <canvas>?
I would like to know how I can set a maximal height for drawing text in a <canvas>
.
As a 4th argument for fillText()
I can give a maximal width, but I also want to limit the vertical space for text, so that all the text which is to开发者_StackOverflow社区o much is just hidden.
Is this possible, and if so, how?
You can't. Not yet. And the spec won't be amended yet for it either, because the spec writer said that implementors already have enough on their plate.
:-(
You can change the font for now, ie right context.font = "72px verdana"
Another note, since you're using text on canvas, is that context.scale(x,y) will scale text perfectly (no pixelation!) so you can use a font that is known to be some number of pixels tall and then scale it perfectly to be precisely as tall or short as you want.
For instance if you knew that sans serif 10point was always 10 pixels tall, you could always draw with that and then scale it up, so if you wanted 50 pixels tall you could do:
context.save()
context.font = "10px sans serif"
context.scale(5,5); // enlarge 5x
context.restore()
Of course, for a lot of fonts just putting 50px/pt may have the same effect.
On the topic of font, its worth noting the difference between px and pt:
http://www.sibagraphics.com/font.php
One more stretchy solution using Template literals:
`ctx.font = `${H*0.75}px sans-serif`
H = max allowed height, 0.75 grants some padding.
NOTE: also useful to limit rotated text width when used with ctx.rotate(90 * Math.PI / 180)
because max-width of fillText(*text*, X, Y, max-width )
limits height after rotation.
精彩评论