The measureText() function
The measureText() function allows you to measure the width of your text. Some browsers also provide extra information as well as the width. RGraph has its own text measuring routine which provides the width and also the height of the text.
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
- The text to measure
An example
<script>
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;
}
</script>