Skip to content

Instantly share code, notes, and snippets.

@huytd
Created May 6, 2016 18:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huytd/327e453c95ca3edadb32d0c867e2561b to your computer and use it in GitHub Desktop.
Save huytd/327e453c95ca3edadb32d0c867e2561b to your computer and use it in GitHub Desktop.
Measure text size in pixels with D3.js
function textSize(text) {
if (!d3) return;
var container = d3.select('body').append('svg');
container.append('text').attr({ x: -99999, y: -99999 }).text(text);
var size = container.node().getBBox();
container.remove();
return { width: size.width, height: size.height };
}
// Usage: textSize("This is a very long text");
// => Return: Object {width: 140, height: 15.453125}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment