更改数字逐渐显示为svg文本,使用D3过渡 [英] Changing number displayed as svg text gradually, with D3 transition

查看:526
本文介绍了更改数字逐渐显示为svg文本,使用D3过渡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个简单的方法来逐步更改显示为svg文本与d3的数字的值。

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.

干杯

推荐答案

看来d3JS已经提供了一个叫做tween的合适的函数。

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/8/

您可以在给定时间间隔内从任何开始到任何结束值,而不管它们的数字精度。

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

它用于SVG文本,但是对于标准的html文本来说也是一样。

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

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

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

这篇关于更改数字逐渐显示为svg文本,使用D3过渡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆