Friday, June 22, 2012

Javascript String Length

Javascript does not provide way to get at the pixel width of a string. There is, of course, the getComputedStyle method, but I wanted another way. This method uses <CANVAS>'s measureText method and accounts for current fontFamily and fontSize:
////////////////////////////////////////////////////////////////////////////////
//
// String.width(OPTIONAL string fontSize, OPTIONAL string fontFamily)
// ==================================================================
// Measures the length of a string, in pixels, using CANVAS's measureText method
// By passing in fontSize and FontFamily, you will get accurate measurements
// eg: x.width('22px','HelveticaNeueLTStdTh')
////////////////////////////////////////////////////////////////////////////////
String.prototype.width = function(fontSize, fontFamily) {
  var ctx = document.createElement('canvas').getContext('2d'),
      retVal = 0,
      theString = this.toString();
  fontSize    = (typeof fontSize==="undefined") ? "12pt" : fontSize;
  fontFamily  = (typeof fontFamily==="undefined") ? "Arial" : fontFamily;
  ctx.font = fontSize + " " + fontFamily;
  return (ctx.measureText(theString).width);
}
Shannon Norrell