Skip to content

Instantly share code, notes, and snippets.

@stephenparish
Created January 8, 2015 16:40
Show Gist options
  • Save stephenparish/f25341c97acfe462e3b2 to your computer and use it in GitHub Desktop.
Save stephenparish/f25341c97acfe462e3b2 to your computer and use it in GitHub Desktop.
vEgxmM
<div id="test-result"></div>
/**
* 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").
*
* @return {Number} the width, rounded up to the nearest whole number.
*
* @see http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
function getTextWidth(text, font, forceHtml) {
font = font || '12px Arial';
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement('canvas'));
var context = canvas.getContext('2d');
// use context to check if canvas is supported
if (context && !forceHtml) {
context.font = font;
var metrics = context.measureText(text);
return Math.ceil(metrics.width);
} else {
var div = document.createElement('div');
document.body.appendChild(div);
div.style.visibility = 'hidden';
div.style.font = font;
div.style.position = "absolute";
div.style.left = -1000;
div.style.top = -1000;
div.style.width = 'auto';
div.style.height = 'auto';
div.style.whiteSpace = 'nowrap';
div.innerHTML = text;
var result = {
width: div.clientWidth,
height: div.clientHeight
};
document.body.removeChild(div);
div = null;
return result.width;
}
}
var testText = "asdfasdfsasdf asdfasdfas akdkadjf jjdjdds";
var fonts = [
'Arial',
'Georgia',
'Helvetica'
];
// this is the allowed difference between the two methods, canvas and dom
var tolerance = 1;
var tests = 0;
var failures = 0;
for (var testFam in fonts) {
for (var i = 2; i < 300; i++) {
var testFont = i + 'px ' + fonts[testFam];
var canvas = getTextWidth(testText, testFont);
var dom = getTextWidth(testText, testFont, true);
if (Math.abs(canvas - dom) > tolerance) {
//document.getElementById('test-result').innerHTML += "Failure: " + testFont + "<br>";
failures++;
}
tests++;
}
}
document.getElementById('test-result').innerHTML += "Total tests: " + tests + "; failures: " + failures;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment