简体   繁体   English

使用javascript计算给定高度的字体宽度

[英]Calculate font width for a given height using javascript

I am looking to develop a tool for width calculation for a given height. 我正在寻找开发用于给定高度的宽度计算的工具。 It will accept font family and font size/height and it should return the total width for the entered text. 它将接受字体系列和字体大小/高度,并且应返回输入文本的总宽度。 I am comparing with https://inkscape.org/en/ tool but width is not appearing to be same. 我正在与https://inkscape.org/en/工具进行比较,但是宽度似乎并不相同。 There are few results I am listing down below for 8 inch height/font size and entered word is 'Custom':- 1 inch = 96 pixel 我在下面列出了8英寸高/字体大小的结果,输入的字词是“自定义”:-1英寸= 96像素

In my tool for these font families: 在我的这些字体系列工具中:

Bhatoshine--21.46"W Bhatoshine--21.46“ W

Madina Clean--20.14"W 麦地那Clean--20.14“ W

Brooklyn Light--28.38"W 布鲁克林之光--28.38“ W

COLLEGE--24.61"W COLLEGE--24.61“ W

In Inkscape desktop tool: 在Inkscape桌面工具中:

Bhatoshine--21.278"W Bhatoshine--21.278“ W

Madina Clean--17.015"W 麦地那Clean--17.015“ W

Brooklyn Light--38.237"W 布鲁克林之光--38.237“ W

COLLEGE--34.857"W College--34.857“ W

I've created this tool based on this example https://www.w3schools.com/tags/canvas_measuretext.asp 我已根据此示例https://www.w3schools.com/tags/canvas_measuretext.asp创建了此工具

I am not able to figure out the mechanism they are using to calculate this. 我无法弄清楚他们用来计算这一点的机制。 Or this difference is because of the behavior of fonts in desktop and web pages. 或这种差异是由于桌面和网页中字体的行为所致。

Any help will be greatly appreciated. 任何帮助将不胜感激。

Thank you 谢谢

Please see below if this can help. 请看下面是否有帮助。 I am using PHP function to try this:- 我正在使用PHP函数尝试此操作:-

function CalculateWidth($text, $InchHeight, $font)
    {

     $height_px = $InchHeight*96;
     $height_px_min = $height_px - 10;
     $height_px_max = $height_px + 10;  
     $OutputArray = array();

     for($i=0;$i<10000;$i++){
        $box = imagettfbbox($i, 0, $font, $text);
      $width = abs($box[2] - $box[0]);
      $height = abs($box[7] - $box[1]);
      if($height > $height_px_min && $height <= $height_px_max){
        $OutputArray[]= number_format($width/96, 2);
      }

 }
 // REMOVE EMPTY VALUES
  $OutputArray = array_filter($OutputArray);

 //CALCULATE AVG OF ALL VALUES
 return $average = number_format(array_sum($OutputArray)/count($OutputArray),2);
}

You can pass the height, path to font file and text to calculate approximate width. 您可以传递高度,字体文件的路径和文本以计算近似宽度。

Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM