Estimate width of text in online study

Hi everyone,

I’m doing some tests for a future experiment in which subjects type letters and what they type is shown on the screen. Depending on the content of the text, I’m then displaying additional text at the end of the typed text. So I need to estimate the width of the text on the screen. When I was testing this offline, I simply used the boundingBox property and it worked beautifully. However, this does not seem to work online: boundingBox doesn’t seem to be a property of the textStim object anymore ( There seems to be a _estimateBoundingBox method but when I try to use it (e.g. by entering: var bb; bb = text._estimateBoundingBox() ), it doesn’t work, I get an error message saying that _estimateBoundingBox() not a function. Is there any way to estimate the width of the text online?

Thank you very much!


Does anyone have any idea? :confused:

I found a way! Based on a post on StackOverFlow. Posting it here for posterity.

So if you define your text units in pixels you can easily get the height in points using conversion formulas/charts easily found online (e.g. 60 pixels = 45pt). Then you can use the function below to estimate the width of your text string.

    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;

var tw = getTextWidth(textstring, "bold 45pt arial"); // here, enter text string and text font in css format

Note: this implementation only estimates the width supposing one single line of text

1 Like