Skip to content

Instantly share code, notes, and snippets.

@nsonnad
Created September 19, 2013 10:51
Show Gist options
  • Save nsonnad/6621805 to your computer and use it in GitHub Desktop.
Save nsonnad/6621805 to your computer and use it in GitHub Desktop.
invisible element to load web font before getBBox needs it
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Text bbox issue</title>
</head>
<style type="text/css" media="screen">
@import url(http://fonts.googleapis.com/css?family=Cutive);
svg text {
font-family: 'Cutive',Helvetica, sans-serif;
font-size: 30px;
}
#invisible {
font-family: 'Cutive',Helvetica, sans-serif;
visibility: hidden;
}
</style>
<body>
<div id="invisible">now you see me...</div>
<div id="content"></div>
</body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var txts;
function transformCoordOf(elem) {
var separator = elem.attr("transform").indexOf(",") > -1 ? "," : " ";
var trans = elem.attr("transform").split(separator);
return { x: (trans[0] ? parseFloat(trans[0].split("(")[1]) : 0), y: (trans[1] ? parseFloat(trans[1].split(")")[0] ): 0) };
}
function positionElements() {
txts.filter(function(d,i){return i != 0})
.attr("transform",function(d,i){
var prev = d3.select(txts[0][i]),
prevWidth = parseFloat(prev.node().getBoundingClientRect().width)
prevCoords = transformCoordOf(prev);
var cur = d3.select(this),
curWidth = parseFloat(cur.node().getBoundingClientRect().width)
curCoords = transformCoordOf(cur);
var y = prevCoords.y,
x = prevCoords.x + prevWidth + 10;
return "translate("+x+","+y+")";
})
d3.select('#invisible').remove();
}
function init() {
var names = ["apples","oranges","bananas"]
var canvas = d3.select("#content")
.append("svg")
.attr("width","600px")
.attr("height","100px");
txts = canvas.selectAll("text").data(names)
.enter()
.append("text")
.attr("transform","translate(10,50)")
.text(function(d){return d});
positionElements();
}
init();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment