Question

Using Raphael JS 2.1.2, the following code:

var distance = 250;
var sizes = [ 14, 18, 24, 48, 72, 96 ];
for(var i = 0; i < sizes.length; i++)
{
  var size = sizes[i];
  var text = me.paper.text(distance + (size * 5), me.top + 200, size).attr({ 'font-size': size });

  var rect = text.getBBox();
  text.paper.rect(rect.x, rect.y, rect.width, rect.height).attr({ stroke: '#FF0000' });
}

produces this output:

Raphael text output

How can I accurately measure the height of the text, as you can see the bounding box includes vertical padding which is relative to the font size?

Also $(text.node).height() returns the same value as rect.height. I am trying to align the top and/or bottom of text with other elements so I need some way to determine the padding or text height per font-size.

I could maintain a collection of { size: [font size], padding: [padding] }, but it would be good if I could generate this at runtime.

Était-ce utile?

La solution

You can't. Actually this is not a "padding". getBBox returns dimentions given from a font metric, not individual glyphs. BBox height for text element includes font ascent and descent.

In most fonts, ascent reserves a gap above cap-height for glyphs such as "Ä". Discenders are reserved for lowercase characters with "tails" such as "g", "j", "q" and etc. For example, draw a rect around text "Äg".

For more detais see:
http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Text http://www.w3.org/TR/SVG11/text.html#BaselineAlignmentProperties http://en.wikipedia.org/wiki/Baseline_(typography)

Autres conseils

It's possible but it's messy. You can do this by using OpenType.js, then drawing a path using same text/size as Raphael with OpenType getPath and measuring the path. You can measure the outputted path with Raphael.pathBBox(path.toPathData()) or (preferable as its faster though more limited browser support) with creating a temp SVG as outlined here.

The size of the path will be the exact size of your text as you desired.

Along the same lines you may also encounter a position challenge i.e. trying to determine how the svg box fits over the raphael box. You can use the ascender/descender values provided by the font object returned from OpenType load alongside with the y/y2 values of your SVG path. All of these will allow you to figure out the baseline of OpenType text and you can match this to your Raphael box.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top