Changing number displayed as svg text gradually, with D3 transition

泪湿孤枕 提交于 2019-12-03 08:46:31

问题


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


回答1:


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));
        };
    });​


来源:https://stackoverflow.com/questions/13454993/changing-number-displayed-as-svg-text-gradually-with-d3-transition

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