是否可以更准确地测量SVG文本高度? [英] Is it possible to more accurately measure SVG text height?

查看:112
本文介绍了是否可以更准确地测量SVG文本高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有SVG文本标记的给定字体来测量用于呈现给定字符串的确切高度。

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

我尝试过使用getBBox和getExtentOfChar,但这两者返回的高度包括渲染的实际文本上方(有时是下方)的一些额外空间。

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
使用此图片中的术语,我试图获得正在渲染的文本的上限高度+下降高度。或者,如果那是不可能的,那就是帽子高度。有没有一种很好的方法来计算这些值?

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?

这是一个快速的代码,显示我正在谈论的额外空间:
http://codepen.io/pcorey/pen/amkGl

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

推荐答案

不。所有SVG DOM方法(getBBox(),getExtentOfChar())都被定义为返回完整的字形单元格高度。帽子高度以上的额外空间允许更高的字形 - 例如重音的大写字母。我认为HTML DOM方法也是如此。

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.

然而,有些JS库可能会被使用。例如:

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.

这篇关于是否可以更准确地测量SVG文本高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆