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 ?...
To find the height of text on an HTML canvas with JavaScript, we can use the canvas context's measureText method. const metrics = ctx. measureText(text); const fontHeight = metrics.
A font is often measured in pt (points). Points dictate the height of the lettering. There are approximately 72 (72.272) points in one inch or 2.54 cm. For example, the font size 72 would be about one inch tall, and 36 would be about a half of an inch.
You can get the width and height of a canvas element simply by accessing those properties of the element. For example: var canvas = document. getElementById('mycanvas'); var width = canvas.
In HTML, you can change the size of text with the <font> tag using the size attribute. The size attribute specifies how large a font will be displayed in either relative or absolute terms. Close the <font> tag with </font> to return to a normal text size.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With