bongbang bongbang - 5 months ago 28
Javascript Question

D3 font-size transition

Why do I get a "fly-in" effect when I try to transition font size in D3? See my minimal example:



<!DOCTYPE html>
<title>Test text transtion</title>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js">
</script>

<body>
<button>Toggle</button>
<script>
var svg = d3.select('body').append('svg')
var myLabel = svg.append('text')
.attr('y', 100)
.text('Watch me.');
var toggle = false;
d3.selectAll('button').on('click', function() {
toggle = !toggle;
myLabel.transition()
.style('font-size', toggle ? '2em' : '1em');
});
</script>
</body>





That is obviously not the desired effect. I just want the text to grow or shrink in place without much fanfare. In another thread, someone else defines a custom tween. Does that mean there's no easier way? I'd be very surprised because this is a commonplace effect, and the built-in interpolator handles opacity and font-weight just fine.

Also if I define a custom tween, does it mean that the other built-in transitions I current have (opacity etc.) will need to be queued since only one transition can be active on a element at a given time?

Answer

text-align="middle" will put the text anchor point in the bottom middle which would seem to be what you want here. If you chain transitions they will operate sequentially.

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!DOCTYPE html>
<title>Test text transtion</title>

<script type="text/javascript"
  src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js">
</script>
<body>
<button>Toggle</button>
<script>
var svg = d3.select('body').append('svg')
var myLabel = svg.append('text')
    .attr('x', 80)
    .attr('y', 100)
    .attr('text-anchor', 'middle')
    .attr('font-size', '1em')
    .text('Watch me.');
var toggle = false;
d3.selectAll('button').on('click', function() {
    toggle = !toggle;
    myLabel.transition()
        .attr('font-size', '2em')
        .duration(500)
        .transition()
        .attr('font-size', '1em')
        .duration(500);
});
</script>
</body>

Comments