The measureText function

Share RGraph:   Share or Like RGraph on Facebook!

The measureText function allows you to measure the horizontal width of your text. It returns an object - the only property of which is the width setting. Unfortunately it does not provide the height - however there are ways around this. The way that RGraph uses is to add the text to a SPAN tag which is positioned off-screen. The .offsetHeight is then read. The text must of course use the same font, size, bold and italic settings as the text that is to be drawn on the canvas.

Adding elements to the DOM like this is a slow process and can slow down animations - so RGraph employs caching so that it's only necessary to do it once.

Arguments to the function

An example

    window.onload = function ()
        var canvas  = document.getElementById("cvs");
        var context = canvas.getContext('2d');

        // Note how the function returns an object of which the width is a property
        width = context.measureText('Some text to measure').width;

See also