开发者

CSS3 @font-face. Get width of imported font

开发者 https://www.devze.com 2023-04-09 10:36 出处:网络
This is how i import the TTF font: @font-face { font-family: bt; src: url(\'Monospace 821 BT.ttf\'); } body {

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
    ];开发者_StackOverflow社区

    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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消