Changing number displayed as svg text gradually, with D3 transition

天涯浪子 提交于 2019-12-02 22:45:39
zbug

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));
        };
    });​
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!