CSS3 @font-face。获取导入字体的宽度
这就是我导入 TTF 字体的方式:
@font-face {
font-family: bt;
src: url('Monospace 821 BT.ttf');
}
body {
font: normal 21px bt;
}
这就是我计算字体字符宽度的方式:
window.onload = function() {
var k = document.createElement('div');
k.innerHTML = 'M';
k.style.position = 'absolute';
document.body.appendChild(k);
var size = [
k.offsetWidth,
k.offsetHeight
];
document.body.removeChild(k);
alert(size[0]+' '+size[1]);
};
使用这种方法,我能够计算宽度和宽度。成功地调整了系统固定宽度字体(如“Monospace”、“Monaco”等)的高度。
但是对于导入的字体,每次将字符“M”更改为其他字符时,我得到的结果都会有所不同。另外,是的,我可以使用导入的字体在屏幕上书写,因此它确实已成功加载到 中。
如何修复这种行为?
This is how i import the TTF font:
@font-face {
font-family: bt;
src: url('Monospace 821 BT.ttf');
}
body {
font: normal 21px bt;
}
And this is how i calculate the Width of font characters:
window.onload = function() {
var k = document.createElement('div');
k.innerHTML = 'M';
k.style.position = 'absolute';
document.body.appendChild(k);
var size = [
k.offsetWidth,
k.offsetHeight
];
document.body.removeChild(k);
alert(size[0]+' '+size[1]);
};
Using this method i am able to calculate the width & height successfully of the system's fixed-width fonts like "Monospace", "Monaco" etc.
But as for the imported font the results I get vary every time i change the character 'M' to something else. Also, YES, i am able to write on-screen with the imported font, so indeed it is successfully loaded in the <body>
.
How can this behavior get fixed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
浏览器以不同的方式处理字偶间距等问题,因此字母之间的间距(即使是等宽字体)不能保证统一。如果字体具有不同的规格,则尤其如此;字符的外观可能相同,但分配给每个字形的实际度量可能更宽或更薄。就数字排版而言,您所看到的并不总是您所得到的。
如果您使用的应用程序需要根据字体大小设置一些任意尺寸,我建议使用相对 CSS 单位,例如
ch
,它与字符“0”的宽度有关,如下所示以元素的当前字体呈现。Browsers handle things like kerning differently, so the spacing between letters (even if it's a monospace font) isn't guaranteed to be uniform. Particularly so if the font has varied metrics; the appearance of the characters might be the same, but the actual metrics assigned to each glyph could be wider or thinner. What you see isn't always what you get as far as digital typography is concerned.
If the application you're using requires setting some arbitrary dimensions based on the font size, I'd suggest using a relative CSS unit instead like
ch
, which pertains to the width of the character "0" as rendered in the element's current typeface.