Calculate width of text string using html5 canvas
HTML
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.min.css">
<span>hello therebbkbik!</span>
CSS
html, body {
font: bold 12px arial;
}
JavaScript
String.prototype.width = function (font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({
'position': 'absolute',
'float': 'left',
'white-space': 'nowrap',
'visibility': 'hidden',
'font': f
})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
};
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
*
* @param 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#21015393
*/
getTextWidth = function(text, font) {
// if given, use cached canvas for better performance
// else, create new canvas
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics;
};
var testText = "hello there!";
var fontDef = "bold 12px arial";
console.log(getTextWidth(testText, fontDef)); // reports 64 in Chrome
console.log(testText.width(fontDef));