Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
bongbang Avatar asked Jun 21 '16 23:06

bongbang


2 Answers

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>
like image 191
Robert Longson Avatar answered Sep 30 '22 04:09

Robert Longson


The fly-in effect happens because you need to specify a font-size first. I ran into that recently. Try adding this before the transition:

.style('font-size', 'Nem')

N = your starting font size. And stick with either style() or attr() for your font options, as mixing the 2 can also cause problems.

like image 35
Dmitry Karpovich Avatar answered Sep 30 '22 06:09

Dmitry Karpovich