0

How would I get the area occupied by a filled ctx.font? For example:

enter image description here

All my research points to baseline and ctx.measureText(word); which gives me the width (perfectly, I should add) but the height is something I'm really struggling with, as descenders seem to always be included in the calculation.

Can I bitmap the font and then calculate the scale that way?

Here is a (failing) canvas size function I was using:

function textSize(word, size){
  var div = document.createElement("div");
  div.innerHTML = word;
  div.style.position = 'absolute';
  div.style.fontFamily = 'serif';
  div.style.fontWeight = 'normal';
  div.style.fontSize = size + 'px';
  document.body.appendChild(div);
  var size = {
    'width': div.offsetWidth,
    'height': div.offsetHeight
  };
  return size; // size.height would be much larger than required with fonts with no descenders
}
Djave
  • 8,595
  • 8
  • 70
  • 124
  • 1
    Maybe you can find answer by [This](http://stackoverflow.com/questions/15161385/how-to-get-the-real-height-of-a-text)? – fuyushimoya Jun 25 '15 at 09:24
  • What about those answers? http://stackoverflow.com/questions/1134586/how-can-you-find-the-height-of-text-on-an-html-canvas – Andrey Jun 25 '15 at 09:49
  • 1
    or this one : http://stackoverflow.com/a/17631567/3702797 – Kaiido Jun 25 '15 at 10:18

1 Answers1

0

try this :

context.fillText("Hello World!", 10, 100);
context.strokeText("Hello World!", 10, 100);
var textMetrics = context.measureText("Hello World!");
var width = textMetrics.width;

context.font = "20pt Arial";
context.fillText("Width of previous text: " + width + "pixels", 10, 150);
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107