元素中水平和垂直放置的等宽字符数

How many monospace characters fit horizontally and vertically in an element?

本文关键字:字符 水平 垂直 元素      更新时间:2023-09-26

我试图找出一个元素中可容纳多少等宽字符(例如 div),知道大小和font-size

例如,我期望结果是:

{
   x: Math.floor(divWidth / fontSize)
 , y: Math.floor(divHeight / lineHeight)
}

但似乎他们是不对的:对于字体大小50pxwidth: 100px,预期的答案将是 2 ,但它3

div {
    font-family: monospace;
    background: black;
    color: lightgreen;
    font-weight: bold;
    width: 100px;
    height: 100px;
    font-size: 50px;
}
<div>
123
123
</div>

对于上面的例子,答案应该是:

{
   x: 3 // 3 chars horizontally
 , y: 1 // 1 char vertically
}

如何自动计算这些值?

var $div = $("div");
var divSize = {
    w: $div.width()
  , h: $div.height()
};
var fontSize = parseInt($div.css("font-size"));

我构建了一个 jQuery 插件来做到这一点:

$.fn.textSize = function () {
    var $self = this;
    function getCharWidth() {
        var canvas = getCharWidth.canvas || (getCharWidth.canvas = $("<canvas>")[0])
          , context = canvas.getContext("2d")
          ;
        
        context.font = [$self.css('font-size'), $self.css('font-family')].join(' ');
        var metrics = context.measureText("3");
        return metrics.width;
    };
    var lineHeight = parseFloat(getComputedStyle($self[0]).lineHeight);
    return {
        x: Math.floor($self.width() / getCharWidth())
      , y: Math.floor($self.height() / lineHeight)
    };
};
alert(JSON.stringify($("div").textSize()));
div {
    font-family: monospace;
    background: black;
    color: lightgreen;
    font-weight: bold;
    width: 100px;
    height: 100px;
    font-size: 50px;
    line-height: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>

你不能这样计算div 中有多少个字符,font-size:50px没有定义每个字符的宽度(只需比较"w"和"l",这些字符不能具有相同的宽度)。

尝试:查找适合多少个字母div并且:http://itnow.blogspot.fr/2009/05/calculating-number-of-characters-that.html

问候