Changing number displayed as svg text gradually, with D3 transition

zbug picture zbug · Nov 19, 2012 · Viewed 13.4k times · Source

I am looking for a simple way to gradually change the value of a number displayed as svg text with d3.

var quality = [0.06, 14];
// qSVG is just the main svg element

qSVG.selectAll(".txt")
    .data(quality)
    .enter()
    .append("text")
    .attr("class", "txt")
    .text(0)
    .transition()
    .duration(1750)
        .text(function(d){
             return d;
        });

Since text in this case is a number i hope there is an easy way to just increment it to the end of the transition.

Maybe someone of you has an idea.

Cheers

Answer

zbug picture zbug · Nov 19, 2012

It seems d3JS already provides a suitable function called "tween"

Here is the important part of the code example.

 .tween("text", function(d) {
        var i = d3.interpolate(this.textContent, d),
            prec = (d + "").split("."),
            round = (prec.length > 1) ? Math.pow(10, prec[1].length) : 1;

        return function(t) {
            this.textContent = Math.round(i(t) * round) / round;
        };
    });​

http://jsfiddle.net/c5YVX/280/

You can increment them over a given time interval from any start to any end value regardless their number precision.

Its implemented for SVG text but of course works the same for standard html text.

If you only need the plain tween function for rounded numbers, it gets a bit more leightweight.

 .tween("text", function(d) {
        var i = d3.interpolate(this.textContent, d),

        return function(t) {
            this.textContent = Math.round(i(t));
        };
    });​