Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

measure text height on an html5 canvas element

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 ?...

like image 204
epeleg Avatar asked Jul 12 '12 12:07

epeleg


People also ask

How do I get text height in canvas?

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.

How do we measure the height of a font character?

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.

How do you measure the height and width of a canvas?

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.

How do I change text height in HTML?

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.


1 Answers

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

like image 75
Michaelangel007 Avatar answered Sep 20 '22 15:09

Michaelangel007