Skip to content

Instantly share code, notes, and snippets.

@ianhirschfeld
Created September 14, 2015 23:14
Show Gist options
  • Save ianhirschfeld/ad718c114354253a6114 to your computer and use it in GitHub Desktop.
Save ianhirschfeld/ad718c114354253a6114 to your computer and use it in GitHub Desktop.
Dynamically adjust a SVG text box so that the font fits a certain width.
var fitTextToWidth = function(node, width) {
var nodeWidth = node.getBBox().width;
if (nodeWidth > width) {
var $node = $(node);
var fontSize = $node.css('font-size');
fontSize = parseInt(fontSize.substring(0, fontSize.length - 2));
fontSize--;
if (fontSize > 0) {
$node.css('font-size', fontSize + 'px');
fitTextToWidth(node, width);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment