简体   繁体   中英

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. There are few results I am listing down below for 8 inch height/font size and entered word is 'Custom':- 1 inch = 96 pixel

In my tool for these font families:

Bhatoshine--21.46"W

Madina Clean--20.14"W

Brooklyn Light--28.38"W

COLLEGE--24.61"W

In Inkscape desktop tool:

Bhatoshine--21.278"W

Madina Clean--17.015"W

Brooklyn Light--38.237"W

COLLEGE--34.857"W

I've created this tool based on this example 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:-

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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