How to determine text width with Javascript


Method 1:

Link CDN:

https://cdn.githubraw.com/piecioshka/cce6ea53ba0db1a4700e/raw/27f9eb81f9419cede3d5ffee5d496f4f35e070b5/getTextWidth.js

Code Javascript:

    /**
     * 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 http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
     */
    function getTextWidth(text, font) {
        // if given, use cached canvas for better performance
        // else, create new canvas
        var canvas = document.createElement("canvas");
        var context = canvas.getContext("2d");
        context.font = font;
        var metrics = context.measureText(text);
        return metrics.width;
    }

Some example:

alert(getTextWidth('Tutorialspots.com',"bold 14px Chakra Petch"))

alert(getTextWidth('Tutorialspots.com',"bold italic 14px Chakra Petch"))

alert(getTextWidth('Tutorialspots.com',"italic 14px Chakra Petch"))

alert(getTextWidth('Tutorialspots.com',"500 14px Chakra Petch"))

alert(getTextWidth('Tutorialspots.com',"normal 14px Chakra Petch"))

Live

Method 2: Konva.js getClientRect() or textWidth
Example:
HTML

<link href="https://fonts.googleapis.com/css?family=Chakra+Petch:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<script src="https://unpkg.com/konva@2.4.2/konva.min.js"></script>
<div id="container" style=""></div>

CSS

#container {
  border: solid 1px black;
  width: 300px;
  height: 300px;
}

Javascript

var stage = new Konva.Stage({
  container: 'container',
  width: 300,
  height: 300
});

var layer = new Konva.Layer();

stage.add(layer);

var text = new Konva.Text({
  x: 10,
  y: 10,
  text: 'Tutorialspots.com',
  fontSize: 14,
  fontFamily: 'Chakra Petch',
  fontStyle: 'normal 500',
  fill: '#000000'
});

layer.add(text)

layer.draw()

console.log(text.getClientRect())

alert(text.getClientRect().width)

Live

Leave a Reply