You need to enable JavaScript to run this app. D3.js在setInterval内首次更新圆环图时transition过渡不生效
优惠活动
大模型
产品
解决方案
定价
更多

D3.js在setInterval内首次更新圆环图时transition过渡不生效

D3.js 圆环图首次更新过渡失效问题

问题背景

我开发了一个用于展示进度的D3.js圆环(donut)图,无法直接展示该图表的实际效果,但提供的示例代码可直接复制运行。
以下是可复现问题的示例代码,此前尝试过多种非常规方案,希望让首次更新时的transition过渡效果正常生效,但问题始终没有解决。查阅的同类线上示例的逻辑与当前代码差异不大,无法定位该异常的触发原因。

可复现代码

HTML 部分

<script src="https://d3js.org/d3.v6.min.js"></script>
<div id="my_dataviz">
    <svg width="300" height="200"> </svg>
    <div id="percentage">0 units</div>
</div>

JS 部分

var data = [95, 5];
var pie = d3.pie().sort(null);
var svg = d3.select("svg"),
    width = svg.attr("width"),
    height = svg.attr("height"),
    radius = Math.min(width, height) / 2;
var arc = d3.arc()
    .innerRadius(60)
    .outerRadius(radius);

function createdonut() {
    g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
    //Inner SVG Circle
    svg.append("svg:circle")
        .attr("cx", width / 2)
        .attr("cy", height / 2)
        .attr("r", 60)
        .style("fill", "#ead4d4")
        // 无效的空g append
        .append("g");
    var color = d3.scaleOrdinal(['#4daf4a', '#377eb8', '#ff7f00', '#984ea3', '#e41a1c']);
    
    //Generate groups
    var arcs = g.selectAll("arc")
        .data(pie(data))
        .enter()
        .append("g")
        .attr("class", "arc")

    //Draw arc paths
    arcs.append("path")
        .attr("fill", function (d, i) {
            return color(i);
        })
        .attr("d", arc)
        .on('mouseover', mouseover);

    function mouseover(d, i) {
        $('#percentage').html(i.data + ' units');
    }
}
function updateDoNut(update) {
    data[0] = data[0] - update;
    data[1] = data[1] + update;

    var path = d3.select("svg").selectAll("path").data(pie(data));
    
    /*path.enter().append("path")
        .attr("fill", function (d, i) {
            return color[i];
        })
        .attr("d", arc);*/

    path.transition().duration(100).attrTween("d", arcTween);
}
function arcTween(a) {
    var i = d3.interpolate(this._current, a);
    this._current = i(0);
    return function (t) {
        return arc(i(t));
    };
}

createdonut();
//updateDoNut(0);
var inter = setInterval(function () { updateDoNut(5); },  3000);

问题根因排查

  • 首次创建路径时,没有给每个path元素初始化_current属性。arcTween第一次执行时读取的this._current为undefined,d3.interpolate(undefined, 新数据)会直接失效,导致第一次更新的过渡完全不生效。
  • 初次生成圆环组元素时,选择器写错:selectAll("arc")是选择<arc>标签元素,实际给元素加的是class="arc",应该用.arc类选择器,后续做绑定更新时会出现元素匹配错误。
  • 选择更新路径时用了全局svg下的所有path,没有绑定到之前创建的圆环路径集,后续如果新增其他path元素会出现绑定错位。
  • D3 v6版本的事件回调参数顺序已经调整,原mouseover的参数逻辑不适配v6,会导致鼠标悬浮时取值错误。
  • 创建中间圆形时多余的空g append是无效代码,无实际作用。
  • 原过渡时长设置为100毫秒,过快的动画也会强化“过渡没生效”的观感。

修正后可正常运行的代码

调整说明

  1. 初始化路径时给每个path设置_current为初始的pie数据,解决首次过渡失效问题
  2. 修正类选择器写法,把圆环路径集存在全局变量里,更新时直接选择绑定,避免元素匹配错误
  3. 适配D3 v6的事件回调参数顺序
  4. 清理无效代码,适当拉长过渡时长优化观感

修正后JS代码

var data = [95, 5];
var pie = d3.pie().sort(null);
var svg = d3.select("svg"),
    width = svg.attr("width"),
    height = svg.attr("height"),
    radius = Math.min(width, height) / 2;
var arc = d3.arc()
    .innerRadius(60)
    .outerRadius(radius);
// 全局保存圆环路径选择集
var arcPaths;
var color = d3.scaleOrdinal(['#4daf4a', '#377eb8', '#ff7f00', '#984ea3', '#e41a1c']);

function createdonut() {
    var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
    // 移除多余的空g append
    svg.append("svg:circle")
        .attr("cx", width / 2)
        .attr("cy", height / 2)
        .attr("r", 60)
        .style("fill", "#ead4d4");
    
    //Generate groups
    var arcs = g.selectAll(".arc")
        .data(pie(data))
        .enter()
        .append("g")
        .attr("class", "arc");

    //Draw arc paths
    arcPaths = arcs.append("path")
        .attr("fill", function (d, i) {
            return color(i);
        })
        .attr("d", arc)
        // 初始化_current
        .each(function(d) { this._current = d; })
        // 适配D3 v6的事件回调参数:(event, d)
        .on('mouseover', function(event, d) {
            $('#percentage').html(d.data + ' units');
        });
}
function updateDoNut(update) {
    data[0] = data[0] - update;
    data[1] = data[1] + update;

    // 直接用之前保存的路径集绑定新数据,避免选错元素
    var path = arcPaths.data(pie(data));
    
    path.transition().duration(1000).attrTween("d", arcTween);
}
function arcTween(a) {
    var i = d3.interpolate(this._current, a);
    this._current = i(0);
    return function (t) {
        return arc(i(t));
    };
}

createdonut();
var inter = setInterval(function () { updateDoNut(5); },  3000);

内容的提问来源于stack exchange,提问作者essessonsee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 19:45:04