Skip to content

Instantly share code, notes, and snippets.

@tlfrd
Last active January 1, 2020 08:41
Show Gist options
  • Save tlfrd/170640240b19a9fa501ce8cc4926c72f to your computer and use it in GitHub Desktop.
Save tlfrd/170640240b19a9fa501ce8cc4926c72f to your computer and use it in GitHub Desktop.
Text Bar Chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
rect { fill: blue; }
text { fill: white; font-family: sans-serif; }
</style>
</head>
<body>
<script>
var textString = "This text fits in the bar quite well",
textId = "text1",
fontSize = 14;
var barSize = { width: 600, height: 100 },
barPosition = { x: 50, y: 50 };
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var rectTextGroup = svg.append("g")
.attr("transform", "translate(" + barPosition.x + "," + barPosition.y + ")")
var rect = rectTextGroup.append("rect")
.attr("width", barSize.width)
.attr("height", barSize.height);
var text = rectTextGroup.append("text")
.attr("id", textId)
.attr("text-anchor", "start")
.text(textString.toUpperCase());
fitTextToRect(text.node(), rect.node(), 1.61);
// This works but there might be a nicer way of calculating this,
// scaling the font instead could be a solution
function fitTextToRect(textNode, rectNode, fontMultiplier) {
var textDimensions = textNode.getBBox(),
rectDimensions = rectNode.getBBox();
var xStretch = rectDimensions.width / textDimensions.width,
yStretch = rectDimensions.height / textDimensions.height;
yStretch = yStretch * fontMultiplier;
text.attr("transform", "scale(" + xStretch + "," + yStretch +")");
text.attr("y", textDimensions.height / fontMultiplier);
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment