Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to more accurately measure SVG text height?

I'm trying to measure the exact height used to render a given string with a given font with an SVG text tag.

I've tried using getBBox and getExtentOfChar, but the height returned by both of these includes some extra space above (and sometimes below) the actual text rendered.

http://upload.wikimedia.org/wikipedia/commons/3/39/Typography_Line_Terms.svg Using the terms in this image, I'm trying to get the either the cap height + descender height of the text being rendered. Or, if that's not possible, just the cap height. Is there a good way to calculate these values?

Here's a quick codepen showing the extra space I'm talking about: http://codepen.io/pcorey/pen/amkGl

HTML:

<div>
  <svg><text>Hello</text></svg>
  <svg><text>Age</text></svg>
</div>

JS:

$(function() {
  $('svg').each(function() {
    var svg = $(this);
    var text = svg.find('text');
     
    var bbox = text.get(0).getBBox();
    svg.get(0).setAttribute('viewBox',
                           [bbox.x,
                            bbox.y,
                            bbox.width,
                            bbox.height].join(' '));
  });
});

I understand that this is a fairly font-specific thing, so this might be totally impossible...

like image 847
pcorey Avatar asked Oct 10 '14 00:10

pcorey


1 Answers

No. All the SVG DOM methods (getBBox(), getExtentOfChar()) are defined to return the full glyph cell height. That extra space above the cap height is allowance for taller glyphs - such as accented capitals. I think this is true for HTML DOM methods as well.

There are, however, JS libraries around which may be of use. For example:

https://github.com/Pomax/fontmetrics.js

I have not used this library myself, so I can't tell you how reliable or accurate it is.

like image 200
Paul LeBeau Avatar answered Nov 09 '22 01:11

Paul LeBeau