Skip to content

Instantly share code, notes, and snippets.

@danasilver
Created August 4, 2016 05:57
Show Gist options
  • Save danasilver/ca7cd790ca38f78d499f99ff91117af1 to your computer and use it in GitHub Desktop.
Save danasilver/ca7cd790ca38f78d499f99ff91117af1 to your computer and use it in GitHub Desktop.
Computed Text Placement

The bar's text is positioned using its computed size to determine if it fits in the bar. Slide the input to change the bar width and the text position.

<!doctype html>
<html>
<head>
<style>
body {
margin: 0;
}
input {
position: absolute;
}
text {
font-family: sans-serif;
font-size: 12px;
}
</style>
</head>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {top: 10, left: 10, bottom: 10, right: 10},
height = 500 - margin.top - margin.bottom,
width = 960 - margin.left - margin.right,
barHeight = 50;
var chart = d3.select('body').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
chart.append('rect')
.attr('x', 0)
.attr('y', height / 2 - barHeight / 2)
.attr('width', width)
.attr('height', barHeight)
.style('stroke', 'black')
.style('fill', 'transparent');
var bar = chart.append('rect')
.attr('x', 0)
.attr('y', height / 2 - barHeight / 2)
.attr('width', .5 * width)
.attr('height', barHeight)
.style('fill', 'steelblue');
var text = chart.append('text')
.attr('y', height / 2 + 6);
d3.select('body').append('input')
.attr('type', 'range')
.style('left', margin.left - 1 + 'px')
.style('top', height / 2 + barHeight + 'px')
.style('width', width + 'px')
.on('input', function() {
update(this.value * 0.01);
});
update(0.5);
function update(percent) {
var fits = text.node().getBBox().width + 5 < percent * width;
text
.transition().duration(50)
.attr('x', percent * width)
.attr('dx', fits ? -5 : 5)
.style('text-anchor', fits ? 'end' : 'start')
.style('fill', fits ? 'white' : 'black')
.text('This bar is ' + d3.format('.0f')(percent * 100) + '% filled');
bar
.transition().duration(50)
.attr('width', percent * width);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment