Changing number displayed as svg text gradually, with D3 transition

前端 未结 1 639
时光取名叫无心
时光取名叫无心 2020-12-29 07:06

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 sv         


        
相关标签:
1条回答
  • 2020-12-29 07:17

    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));
            };
        });​
    
    0 讨论(0)
提交回复
热议问题