Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing number displayed as svg text gradually, with D3 transition

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

like image 499
zbug Avatar asked Nov 19 '12 13:11

zbug


People also ask

What does SVG stand for how are they used with D3?

SVG stands for Scalable Vector Graphics. SVG is an XML-based vector graphics format. It provides options to draw different shapes such as Lines, Rectangles, Circles, Ellipses, etc. Hence, designing visualizations with SVG gives you more power and flexibility.

Does D3 use SVG?

SVG is a markup language for graphics. D3 is not limited to SVG. You can also use D3 to create visualizations using canvas, HTML elements, for example.

What is D3 and SVG?

js (also known as D3, short for Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. It makes use of Scalable Vector Graphics (SVG), HTML5, and Cascading Style Sheets (CSS) standards. It is the successor to the earlier Protovis framework.

Does D3 use canvas or SVG?

D3 charts are most often rendered using SVG, a retained mode graphics model, which is easy to use, but performance is limited. SVG charts can typically handle around 1,000 datapoints. Since D3 v4 you've also had the option to render charts using canvas, which is an immediate mode graphics model.


1 Answers

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));
        };
    });​
like image 104
zbug Avatar answered Oct 15 '22 16:10

zbug