テキストの長さを元に、divなどに収まるサイズのフォントサイズを計算するJSのメモ

テキストの長さを元に、divなどに収まるサイズのフォントサイズを計算するJSのメモ:

なんかCSSとかJSでライブラリすでにありそうだったけど、自前で実装したほうが早そうだったので。


やりたいこと

以下条件をもつときに、見切れたりすることなくテキストを表示したい。

  • divやpタグ内にテキストを挿入し表示する。
  • divやpタグの横幅は、一定ではない。
  • 表示したいテキストの文字数は一定ではない。
  • テキストは横向きに1行で表示し、改行はしない。ありえない。


補足:

  • ViewportWidth 等は、テキストが一定ではないため使え無い。


実装


function

function divideBoxwitdhAndPxPerText(boxWidthPx, pxPerText) { 
  return boxWidthPx / pxPerText; 
} 
 
function makeBetterFontSize(boxWidthPx, text){ 
  // Default is 15.(font-size:30px) for my proj. 
  var pxPerText = 15; 
  if (boxWidthPx < 1) { 
    console.warn('`boxWidthPx` must be over 1.'); 
    return pxPerText * 2; 
  } 
  if (typeof boxWidth !== 'number') { 
    console.warn('`boxWidthPx` is not Number. return default font-size.'); 
    return pxPerText * 2; 
  } 
  if (typeof text !== 'string') { 
    console.warn('`text` is not String. return default font-size.'); 
    return pxPerText * 2; 
  } 
  while(pxPerText > 0) { 
    var maxTextLength = divideBoxwitdhAndPxPerText(boxWidthPx, pxPerText); 
    if (text.length <= maxTextLength) { 
      break; 
    } 
    pxPerText -= 1; 
  } 
  if (pxPerText === 0) { 
    pxPerText = 0.5; 
  } 
  // Font-size is `pxPerText * 2` for my proj. 
  return pxPerText * 2; 
} 


使い方

var boxWidth = 271; 
var text = "999999999.99999999"; 
console.log("A", makeBetterFontSize(boxWidth, text)); 
// 30 
 
boxWidth = 271; 
text = "9999999999999.99999999"; 
console.log("B", makeBetterFontSize(boxWidth, text)); 
// 26 
 
boxWidth = 300; 
text = "9999999999999.99999999"; 
console.log("C", makeBetterFontSize(boxWidth, text)); 
// 30 
 
boxWidth = 30; 
text = "9999999999999.99999999"; 
console.log("D", makeBetterFontSize(boxWidth, text)); 
// 2 
 
boxWidth = 20; 
text = "9999999999999.99999999"; 
console.log("E", makeBetterFontSize(boxWidth, text)); 
// 1 
 
boxWidth = 271; 
text = "9.99999999"; 
console.log("F", makeBetterFontSize(boxWidth, text)); 
// 30 
 
boxWidth = "あああ"; 
text = "ほ"; 
console.log("G", makeBetterFontSize(boxWidth, text)); 
// 30 
// ⚠️がでる。使い方が間違ってる。 
 
boxWidth = 300; 
text = []; 
console.log("H", makeBetterFontSize(boxWidth, text)); 
// 30 
// ⚠️がでる。使い方が間違ってる。 
 
boxWidth = 0; 
text = "111.0"; 
console.log("I", makeBetterFontSize(boxWidth, text)); 
// 30 
// ⚠️がでる。使い方が間違ってる。 


補足

boxWidth には実際のpxが入るので以下みたいなのをつかう想定。

var boxWidth = document.getElementById('my-id').clientWidth; 
以上。

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)