Reputation: 10945
I know I can use context.measureText to get the width of some text if it would now be rendered on the canvas. Is there a way to do the same but get the text's height?
just a thought to myself - maybe I can rotate the text 90Deg and then test for the width ?...
Upvotes: 15
Views: 33585
Reputation: 667
I had the same issue and what I found is this. Get the font size from you string. I do not know why, but it only works when you set the proprety in PT, not PX.
ctx.font="20px Georgia"; // This will not work.
ctx.font="20pt Georgia"; // This is what we need.
Then take the value from it.
var txtHeight = parseInt(ctx.font);
Now you have the height for your text. Like I said, in my side I had to set the size in PT as PX
Upvotes: 5
Reputation: 3077
This SO answer is probably over-engineered for your needs How can you find the height of text on an HTML canvas?
I prefer something a little more simple:
var text = "Hello World";
var font = "Serif";
var size = "16";
var bold = false;
var div = document.createElement("div");
div.innerHTML = text;
div.style.position = 'absolute';
div.style.top = '-9999px';
div.style.left = '-9999px';
div.style.fontFamily = font;
div.style.fontWeight = bold ? 'bold' : 'normal';
div.style.fontSize = size + 'pt'; // or 'px'
document.body.appendChild(div);
var size = [ div.offsetWidth, div.offsetHeight ];
document.body.removeChild(div);
// Output
console.log( size );
var pre = document.getElementById( "output" );
if( pre )
pre.innerHTML = size;
<pre id="output"></pre>
Reference: http://www.rgraph.net/blog/2013/january/measuring-text-height-with-html5-canvas.html
Upvotes: 6
Reputation: 12431
You can set the font size of your canvas in pixels which you SHOULD then be able to use as the height of your text box. However, when I came to do this I found I needed to add approximately 50% to the pixel height to get an accurate value:
var textHeight = fontSize * 1.5;
If that's not good enough for you, there are a couple of pretty full-blown solutions outlined here, one of which uses the getImageData
method to count the number of vertical pixels.
Upvotes: 1