Javascript 如何通过d3设置线图路径的动画?

Javascript 如何通过d3设置线图路径的动画?,javascript,d3.js,Javascript,D3.js,我试图在d3中画出这条线图(这样当它第一次加载时,它会给出一个绘图动画)。在我的代码笔的第86-95行,我有我认为应该用来画出来的代码,但是没有动画发生 var totalLength = path.node().getTotalLength(); path .attr("stroke-dasharray", totalLength + " " + totalLength) .attr("stroke-dashoffset", totalLength) .trans

我试图在d3中画出这条线图(这样当它第一次加载时,它会给出一个绘图动画)。在我的代码笔的第86-95行,我有我认为应该用来画出来的代码,但是没有动画发生

var totalLength = path.node().getTotalLength();

  path
    .attr("stroke-dasharray", totalLength + " " + totalLength)
    .attr("stroke-dashoffset", totalLength)
    .transition()
    .duration(4000)
    .ease(d3.easeLinear)
    .attr("stroke-dashoffset", 0)
    .on("end", repeat);


谢谢

简单的修复方法是在调用
path.attr…transition()上的动画时,将行附加到变量
path

所以基本上是这样做的:

      // Add the line
      let path = svg
        .append("path")
        .datum(data)
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-width", 1.5)
        .attr("d", d3.line()
          .x(function(d) { return x(d.x) })
          .y(function(d) { return y(d.y) })
          )
完整片段


//设置图形的尺寸和边距
var margin={顶部:10,右侧:30,底部:30,左侧:60},
宽度=460-margin.left-margin.right,
高度=400-margin.top-margin.bottom;
//将svg对象附加到页面主体
var svg=d3。选择(“我的数据维”)
.append(“svg”)
.attr(“宽度”,宽度+边距。左侧+边距。右侧)
.attr(“高度”,高度+边距。顶部+边距。底部)
.附加(“g”)
.attr(“转换”,
“翻译(“+margin.left+”,“+margin.top+”);
//读取数据
d3.csv(“https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_IC.csv,函数(数据){
//添加X轴-->它是一种日期格式
var x=d3.scaleLinear()
.domain([1100])
.范围([0,宽度]);
svg.append(“g”)
.attr(“变换”、“平移(0)”、“高度+”)
.call(d3.axisBottom(x));
//添加Y轴
变量y=d3.scaleLinear()
.domain([0,13])
.范围([高度,0]);
svg.append(“g”)
.调用(d3.左(y));
//这样可以找到鼠标最近的X索引:
var-bisect=d3.平分线(函数(d){return d.x;});
//创建沿图表曲线移动的圆
var focus=svg
.append('g')
.append('圆')
.style(“填充”、“无”)
.attr(“笔划”、“黑色”)
.attr('r',8.5)
.style(“不透明度”,0)
//创建沿图表曲线移动的文本
var focusText=svg
.append('g')
.append('文本')
.style(“不透明度”,0)
.attr(“文本锚定”、“左”)
.attr(“路线基线”、“中间”)
//在svg区域顶部创建一个矩形:该矩形恢复鼠标位置
svg
.append('rect')
.style(“填充”、“无”)
.style(“指针事件”、“全部”)
.attr('width',width)
.attr('height',height)
.on('mouseover',mouseover)
.on('mousemove',mousemove)
.on('mouseout',mouseout);
//添加行
let path=svg
.append(“路径”)
.基准(数据)
.attr(“填充”、“无”)
.attr(“笔划”、“钢蓝”)
.attr(“笔划宽度”,1.5)
.attr(“d”,d3.line()
.x(函数(d){返回x(d.x)})
.y(函数(d){返回y(d.y)})
)
var totalLength=path.node().getTotalLength();
路径
.attr(“笔划数组”,总长度+“”+总长度)
.attr(“行程偏移”,总长度)
.transition()
.持续时间(4000)
.ease(d3.easeLinear)
.attr(“笔划偏移量”,0)
.打开(“结束”,重复);
//当鼠标移动->在正确位置显示注释时会发生什么。
函数mouseover(){
焦点样式(“不透明度”,1)
focusText.style(“不透明度”,1)
}
函数mousemove(){
//恢复我们需要的坐标
var x0=x.invert(d3.鼠标(this)[0]);
var i=对分(数据,x0,1);
selectedData=数据[i]
集中
.attr(“cx”,x(selectedData.x))
.attr(“cy”,y(selectedData.y))
focusText
.html(“x:+selectedData.x+”-“+”y:+selectedData.y)
.attr(“x”,x(selectedData.x)+15)
.attr(“y”,y(selectedData.y))
}
函数mouseout(){
focus.style(“不透明度”,0)
focusText.style(“不透明度”,0)
}
})

这正是我想要做的。非常感谢你的帮助!