質問

JavaScriptを使用して文字列の幅を計算したいと考えています。これは等幅書体を使用しなくても可能ですか?

それが組み込まれていない場合、私の唯一のアイデアは、各文字の幅のテーブルを作成することですが、これは特にサポートにはかなり不合理です ユニコード 文字サイズも異なります (さらに言えば、すべてのブラウザも同様です)。

役に立ちましたか?

解決

次のスタイルでスタイル設定された DIV を作成します。JavaScript で、測定するフォント サイズと属性を設定し、DIV に文字列を入力して、DIV の現在の幅と高さを読み取ります。コンテンツに合わせて拡大され、サイズは文字列のレンダリング サイズの数ピクセル以内になります。

var fontSize = 12;
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px"

console.log(height, width);
#Test
{
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
    white-space: nowrap; /* Thanks to Herb Caudill comment */
}
<div id="Test">
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</div>

他のヒント

HTML5, を使用できます。 Canvas.measureText メソッド (さらなる説明 ここ).

このフィドルを試してください:

/**
 * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
 * 
 * @param {String} text The text to be rendered.
 * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
 * 
 * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
function getTextWidth(text, font) {
    // re-use canvas object for better performance
    var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
}

console.log(getTextWidth("hello there!", "bold 12pt arial"));  // close to 86

このフィドル この Canvas メソッドを次のバリエーションと比較します。 Bob Monteverde の DOM ベースのメソッド, 、結果の精度を分析および比較できます。

このアプローチには、次のようないくつかの利点があります。

注記:DOM にテキストを追加するときは、次のことも考慮してください。 パディング、マージン、ボーダー.

注2:一部のブラウザでは、このメソッドによりサブピクセル精度が得られます (結果は浮動小数点数になります)。また、そうでないブラウザもあります (結果は int のみです)。走りたくなるかもしれません Math.floor (または Math.ceil) 結果に基づいて、不一致を回避します。DOM ベースの方法は決してサブピクセル精度ではないため、この方法は他の方法よりもさらに高い精度を持っています。

によると このjsperf (コメントの寄稿者に感謝します)、 Canvasメソッド そしてその DOMベースのメソッド キャッシュが追加された場合、ほぼ同等の速度になります。 DOMベースのメソッド Firefox を使用していません。Firefox では、何らかの理由でこれが Canvasメソッド よりもはるかに高速です DOMベースのメソッド (2014年9月現在)。

これは例なしで私がまとめたものです。私たち全員が同じ認識を持っているようです。

String.prototype.width = function(font) {
  var f = font || '12px arial',
      o = $('<div></div>')
            .text(this)
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}

使い方は簡単です: "a string".width()

**追加した white-space: nowrap そのため、ウィンドウの幅よりも大きな幅の文字列を計算できます。

jQuery:

(function($) {

 $.textMetrics = function(el) {

  var h = 0, w = 0;

  var div = document.createElement('div');
  document.body.appendChild(div);
  $(div).css({
   position: 'absolute',
   left: -1000,
   top: -1000,
   display: 'none'
  });

  $(div).html($(el).html());
  var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
  $(styles).each(function() {
   var s = this.toString();
   $(div).css(s, $(el).css(s));
  });

  h = $(div).outerHeight();
  w = $(div).outerWidth();

  $(div).remove();

  var ret = {
   height: h,
   width: w
  };

  return ret;
 }

})(jQuery);

これは私にとってはうまくいきます...

// Handy JavaScript to measure the size taken to render the supplied text;
// you can supply additional style information too if you have it.

function measureText(pText, pFontSize, pStyle) {
    var lDiv = document.createElement('div');

    document.body.appendChild(lDiv);

    if (pStyle != null) {
        lDiv.style = pStyle;
    }
    lDiv.style.fontSize = "" + pFontSize + "px";
    lDiv.style.position = "absolute";
    lDiv.style.left = -1000;
    lDiv.style.top = -1000;

    lDiv.innerHTML = pText;

    var lResult = {
        width: lDiv.clientWidth,
        height: lDiv.clientHeight
    };

    document.body.removeChild(lDiv);
    lDiv = null;

    return lResult;
}

ExtJS JavaScript ライブラリ Ext.util.TextMetrics という優れたクラスがあり、「テキスト ブロックの正確なピクセル測定値を提供するため、特定のテキスト ブロックの高さと幅をピクセル単位で正確に判断できます」。これを直接使用することも、ソースからコードまで表示して、これがどのように行われるかを確認することもできます。

http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html

そのためのちょっとしたツールを書きました。おそらくそれは誰かの役に立つでしょう。それは動作します jQueryなし.

https://github.com/schickling/calculate-size

使用法:

var size = calculateSize("Hello world!", {
   font: 'Arial',
   fontSize: '12px'
});

console.log(size.width); // 65
console.log(size.height); // 14

フィドル: http://jsfiddle.net/PEvL8/

静的な文字幅マップを実行するという「唯一のアイデア」が気に入っています。実際、私の目的にはうまく機能します。場合によっては、パフォーマンス上の理由から、または DOM に簡単にアクセスできないために、単一フォントに合わせて調整された簡単なスタンドアロン電卓が必要になる場合があります。これが Helvetica に合わせて調整されたものです。文字列と (オプションで) フォント サイズを渡します。

function measureText(str, fontSize = 10) {
  const widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.2796875,0.2765625,0.3546875,0.5546875,0.5546875,0.8890625,0.665625,0.190625,0.3328125,0.3328125,0.3890625,0.5828125,0.2765625,0.3328125,0.2765625,0.3015625,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.2765625,0.2765625,0.584375,0.5828125,0.584375,0.5546875,1.0140625,0.665625,0.665625,0.721875,0.721875,0.665625,0.609375,0.7765625,0.721875,0.2765625,0.5,0.665625,0.5546875,0.8328125,0.721875,0.7765625,0.665625,0.7765625,0.721875,0.665625,0.609375,0.721875,0.665625,0.94375,0.665625,0.665625,0.609375,0.2765625,0.3546875,0.2765625,0.4765625,0.5546875,0.3328125,0.5546875,0.5546875,0.5,0.5546875,0.5546875,0.2765625,0.5546875,0.5546875,0.221875,0.240625,0.5,0.221875,0.8328125,0.5546875,0.5546875,0.5546875,0.5546875,0.3328125,0.5,0.2765625,0.5546875,0.5,0.721875,0.5,0.5,0.5,0.3546875,0.259375,0.353125,0.5890625]
  const avg = 0.5279276315789471
  return str
    .split('')
    .map(c => c.charCodeAt(0) < widths.length ? widths[c.charCodeAt(0)] : avg)
    .reduce((cur, acc) => acc + cur) * fontSize
}

その巨大で醜い配列は、文字コードによってインデックス付けされた ASCII 文字幅です。したがって、これは ASCII のみをサポートします (それ以外の場合は、平均的な文字幅を想定します)。幸いなことに、幅は基本的にフォント サイズに比例して変化するため、どのフォント サイズでも非常にうまく機能します。カーニングや合字などに対する認識が著しく欠けています。

「調整」するために、svg 上で charCode 126 (強力なチルダ) までのすべての文字をレンダリングし、境界ボックスを取得してこの配列に保存しました。 詳しいコード、説明、デモはこちら.

キャンバスを使用できるため、CSS プロパティをあまり扱う必要がありません。

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "20pt Arial";  // This can be set programmaticly from the element's font-style if desired
var textWidth = ctx.measureText($("#myElement").text()).width;
<span id="text">Text</span>

<script>
var textWidth = document.getElementById("text").offsetWidth;
</script>

これは、<span> タグに他のスタイルが適用されていない限り機能します。offsetWidth には、境界線の幅、水平方向のパディング、垂直スクロールバーの幅などが含まれます。

以下のコードは、スパンタグの幅を「計算」し、長すぎる場合は「...」を追加し、親に収まるまで (またはそれ以上の試行が行われるまで) テキストの長さを減らします。千回)

CSS

div.places {
  width : 100px;
}
div.places span {
  white-space:nowrap;
  overflow:hidden;
}

HTML

<div class="places">
  <span>This is my house</span>
</div>
<div class="places">
  <span>And my house are your house</span>
</div>
<div class="places">
  <span>This placename is most certainly too wide to fit</span>
</div>

JavaScript (jQuery を使用)

// loops elements classed "places" and checks if their child "span" is too long to fit
$(".places").each(function (index, item) {
    var obj = $(item).find("span");
    if (obj.length) {
        var placename = $(obj).text();
        if ($(obj).width() > $(item).width() && placename.trim().length > 0) {
            var limit = 0;
            do {
                limit++;
                                    placename = placename.substring(0, placename.length - 1);
                                    $(obj).text(placename + "...");
            } while ($(obj).width() > $(item).width() && limit < 1000)
        }
    }
});

このコードを試してください:

function GetTextRectToPixels(obj)
{
var tmpRect = obj.getBoundingClientRect();
obj.style.width = "auto"; 
obj.style.height = "auto"; 
var Ret = obj.getBoundingClientRect(); 
obj.style.width = (tmpRect.right - tmpRect.left).toString() + "px";
obj.style.height = (tmpRect.bottom - tmpRect.top).toString() + "px"; 
return Ret;
}

テキストの幅と高さは次のように取得できます。 clientWidth そして clientHeight

var element = document.getElementById ("mytext");

var width = element.clientWidth;
var height = element.clientHeight;

スタイルの位置プロパティが絶対に設定されていることを確認してください

element.style.position = "absolute";

の中にある必要はない div, の中に入れることができます p または span

より良い方法は、要素を表示する直前にテキストが適合するかどうかを検出することです。したがって、要素が画面上にある必要がないこの関数を使用できます。

function textWidth(text, fontProp) {
    var tag = document.createElement("div");
    tag.style.position = "absolute";
    tag.style.left = "-999em";
    tag.style.whiteSpace = "nowrap";
    tag.style.font = fontProp;
    tag.innerHTML = text;

    document.body.appendChild(tag);

    var result = tag.clientWidth;

    document.body.removeChild(tag);

    return result;
}

使用法:

if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
    ...
}

から構築 ディーパック・ナダールの答え, テキストとフォントのスタイルを受け入れるように関数のパラメーターを変更しました。要素を参照する必要はありません。また、 fontOptions にはデフォルトがあるため、すべてを指定する必要はありません。

(function($) {
  $.format = function(format) {
    return (function(format, args) {
      return format.replace(/{(\d+)}/g, function(val, pos) {
        return typeof args[pos] !== 'undefined' ? args[pos] : val;
      });
    }(format, [].slice.call(arguments, 1)));
  };
  $.measureText = function(html, fontOptions) {
    fontOptions = $.extend({
      fontSize: '1em',
      fontStyle: 'normal',
      fontWeight: 'normal',
      fontFamily: 'arial'
    }, fontOptions);
    var $el = $('<div>', {
      html: html,
      css: {
        position: 'absolute',
        left: -1000,
        top: -1000,
        display: 'none'
      }
    }).appendTo('body');
    $(fontOptions).each(function(index, option) {
      $el.css(option, fontOptions[option]);
    });
    var h = $el.outerHeight(), w = $el.outerWidth();
    $el.remove();
    return { height: h, width: w };
  };
}(jQuery));

var dimensions = $.measureText("Hello World!", { fontWeight: 'bold', fontFamily: 'arial' });

// Font Dimensions: 94px x 18px
$('body').append('<p>').text($.format('Font Dimensions: {0}px x {1}px', dimensions.width, dimensions.height));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

他の誰かが文字列の幅を測定する方法を探してここに来た場合に備えて そして 特定の幅に収まる最大のフォント サイズを知る方法。これは、バイナリ検索を使用した @Domi のソリューションに基づいて構築された関数です。

/**
 * Find the largest font size (in pixels) that allows the string to fit in the given width.
 * 
 * @param {String} text The text to be rendered.
 * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold ?px verdana") -- note the use of ? in place of the font size.
 * @param {width} the width in pixels the string must fit in
 * @param {minFontPx} the smallest acceptable font size in pixels
 * @param {maxFontPx} the largest acceptable font size in pixels
**/
function GetTextSizeForWidth( text, font, width, minFontPx, maxFontPx )
{
    for ( ; ; )
    {
        var s = font.replace( "?", maxFontPx );
        var w = GetTextWidth( text, s );
        if ( w <= width )
        {
            return maxFontPx;
        }

        var g = ( minFontPx + maxFontPx ) / 2;

        if ( Math.round( g ) == Math.round( minFontPx ) || Math.round( g ) == Math.round( maxFontPx ) )
        {
            return g;
        }

        s = font.replace( "?", g );
        w = GetTextWidth( text, s );
        if ( w >= width )
        {
            maxFontPx = g;
        }
        else
        {
            minFontPx = g;
        }
    }
}

これは Depak のエントリーにかなり似ていると思いますが、これは、ある記事で公開された Louis Lazaris の作品に基づいています。 印象的なウェブページ

(function($){

        $.fn.autofit = function() {             

            var hiddenDiv = $(document.createElement('div')),
            content = null;

            hiddenDiv.css('display','none');

            $('body').append(hiddenDiv);

            $(this).bind('fit keyup keydown blur update focus',function () {
                content = $(this).val();

                content = content.replace(/\n/g, '<br>');
                hiddenDiv.html(content);

                $(this).css('width', hiddenDiv.width());

            });

            return this;

        };
    })(jQuery);

fit イベントは、関数がコントロールに関連付けられた直後に関数呼び出しを実行するために使用されます。

例えば。:$('input').autofit().trigger("fit");

jQuery を使用しない場合:

String.prototype.width = function (fontSize) {
    var el,
        f = fontSize + " px arial" || '12px arial';
    el = document.createElement('div');
    el.style.position = 'absolute';
    el.style.float = "left";
    el.style.whiteSpace = 'nowrap';
    el.style.visibility = 'hidden';
    el.style.font = f;
    el.innerHTML = this;
    el = document.body.appendChild(el);
    w = el.offsetWidth;
    el.parentNode.removeChild(el);
    return w;
}

// Usage
"MyString".width(12);

動作例のフィドル: http://jsfiddle.net/tdpLdqpo/1/

HTML:

<h1 id="test1">
    How wide is this text?
</h1>
<div id="result1"></div>
<hr/>
<p id="test2">
    How wide is this text?
</p>
<div id="result2"></div>
<hr/>
<p id="test3">
    How wide is this text?<br/><br/>
    f sdfj f sdlfj lfj lsdk jflsjd fljsd flj sflj sldfj lsdfjlsdjkf sfjoifoewj flsdjfl jofjlgjdlsfjsdofjisdojfsdmfnnfoisjfoi  ojfo dsjfo jdsofjsodnfo sjfoj ifjjfoewj fofew jfos fojo foew jofj s f j
</p>
<div id="result3"></div>

JavaScript コード:

function getTextWidth(text, font) {
    var canvas = getTextWidth.canvas ||
        (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
};

$("#result1")
.text("answer: " +
    getTextWidth(
             $("#test1").text(),
             $("#test1").css("font")) + " px");

$("#result2")
    .text("answer: " +
        getTextWidth(
             $("#test2").text(),
             $("#test2").css("font")) + " px");

$("#result3")
    .text("answer: " +
        getTextWidth(
             $("#test3").text(),
             $("#test3").css("font")) + " px");

Element.getClientRects() メソッドは次のコレクションを返します DOMRect クライアント内の各 CSS 境界ボックスの境界四角形を示すオブジェクト。戻り値は次のコレクションです。 DOMRect 要素に関連付けられた CSS 境界ボックスごとに 1 つずつオブジェクト。それぞれ DOMRect オブジェクトには読み取り専用が含まれています left, top, right そして bottom ビューポートの左上を基準にして左上を指定して境界ボックスをピクセル単位で記述するプロパティ。

Element.getClientRects() による Mozilla の貢献者 以下にライセンスされています CC-BY-SA 2.5.

返されたすべての四角形の幅を合計すると、テキストの合計幅がピクセル単位で求められます。

document.getElementById('in').addEventListener('input', function (event) {
    var span = document.getElementById('text-render')
    span.innerText = event.target.value
    var rects = span.getClientRects()
    var widthSum = 0
    for (var i = 0; i < rects.length; i++) {
        widthSum += rects[i].right - rects[i].left
    }
    document.getElementById('width-sum').value = widthSum
})
<p><textarea id='in'></textarea></p>
<p><span id='text-render'></span></p>
<p>Sum of all widths: <output id='width-sum'>0</output>px</p>

小さな ES6 モジュールを作成しました (jQuery を使用):

import $ from 'jquery';

const $span=$('<span>');
$span.css({
    position: 'absolute',
    display: 'none'
}).appendTo('body');

export default function(str, css){
    $span[0].style = ''; // resetting the styles being previously set
    $span.text(str).css(css || {});
    return $span.innerWidth();
}

使いやすい:

import stringWidth from './string_width';
const w = stringWidth('1-3', {fontSize: 12, padding: 5});

素晴らしいことに気づくかもしれません。これにより、パディングも含め、あらゆる CSS 属性を考慮できるようになります。

var textWidth = (function (el) {
    el.style.position = 'absolute';
    el.style.top = '-1000px';
    document.body.appendChild(el);

    return function (text) {
        el.innerHTML = text;
        return el.clientWidth;
    };
})(document.createElement('div'));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top