Calculate text width with JavaScript

前端 未结 24 1679
陌清茗
陌清茗 2020-11-21 05:08

I\'d like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?

If it\'s not built-in, my only idea is t

24条回答
  •  囚心锁ツ
    2020-11-21 05:40

    Fiddle of working example: http://jsfiddle.net/tdpLdqpo/1/

    HTML:

    How wide is this text?


    How wide is this text?


    How wide is this text?

    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

    JavaScript code:

    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");
    

提交回复
热议问题