LoginSignup
5
3

More than 5 years have passed since last update.

JavaScriptでテキストの幅を取得する方法

Last updated at Posted at 2018-12-05

描画する前にテキスト幅を事前取得したい場合に使える。

clientWidth を使った方法

clientWidthを使った方法
    const span = document.createElement('span');
    span.style.position = 'absolute';
    span.style.top = '-9999px';
    span.style.fontSize = '13px';
    span.style.fontFamily = 'Segoe UI';
    span.textContent = 'あいうえお';
    // 一旦 DOM Tree に append しないといけない
    document.body.appendChild(span);
    console.log(span.clientWidth);
    // 幅を取得したら remove
    document.body.removeChild(span);

事前にとはいいつつも、一旦 DOM に追加しているので、あまりよろしくない。

measureText を使った方法

measureTextを使った方法
    // canvas は DOM Tree に append しなくてもいい
    const ctx = document.createElement('canvas').getContext('2d');
    ctx.font = '13px "Segoe UI"';
    console.log(ctx.measureText('あいうえお').width);

簡潔。

結論

measureText を使った方法が簡潔で良い。DOM Tree を汚さなくて済むのも良い。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3