我正在尝试创建动画弧形图。我已经能够创建所需的动画类型,但是我想添加一个延迟。
要创建动画,我使用.attrTween方法。
这是我的延迟尝试代码的主要部分:
svg.selectAll(".arcs")
.data(data)
.enter()
.append("path")
.style("stroke", "#832129")
.attr("class", "arc")
.attr("d", function(d){
var To_scale = xScale(d.experience),
From_scale = xScale(0),
y = yScale(0),
dx = To_scale - From_scale,
dy = y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + From_scale + " " + y + " A 43 50 0 0 1 " + To_scale + " " + y;
})
.style("fill", "none")
.style("opacity", 1)
.call(transition)
.on("mouseover", function(d){
var thisClass = d3.select(this).attr("class")
d3.select(this).style("stroke", "white").style("opacity", 1)
d3.selectAll(".arcs").style("opacity", 0.1)
})
.on("mouseout", function(d){
d3.select(this).style("stroke", "#832129").style("opacity", 1)
})
// DELAY ATTEMPT HERE
function transition(path){
path.transition()
.delay(function(d, i){ return i * 1000})
.duration(2500)
.attrTween("stroke-dasharray", tweenDash)
}
function tweenDash(){
var l = this.getTotalLength(),
i = d3.interpolateString("0," + l, l + "," + l)
return function(t){ return i(t); };
}
这种方法的问题在于,它只会使图表出现而没有延迟或动画。我也尝试过
.delay(100)
,但这只会延迟动画。我希望延迟/动画看起来像这样的https://twitter.com/sxywu/status/937510554310123520,其中弧形一个接一个地出现。我只是对为什么
.delay(function(d, i){ return i * 1000})
不起作用感到困惑。我的完整代码可以在我的bl.ocks页面上看到:https://bl.ocks.org/JulienAssouline/7236f0632102c6e2d3399208c4c90c26
谢谢。
最佳答案
将圆弧的opacity
设置为0:
svg.selectAll(".arcs")
.data(data)
.enter()
.append("path")
...
.style("opacity", 0) // <== !!!
...
并以此方式重写
transition
函数:function transition(path){
path.each(function(pathItem, index) {
d3.select(this).transition()
.delay(index + 200)
.duration(index * 5 + 1000)
.on('start',function() {
d3.select(this).style("opacity", 1)
})
.attrTween("stroke-dasharray", tweenDash)
})
}
在这里,我们为您选择的每个项目分别指定一个过渡参数。您可以根据需要使用
delay
和duration
值。检查working example based on your code。我在这里将部分csv数据硬编码(所有路径都会绘制完整的数据集),以便能够使用jsFiddle,但所有其他代码都相同。
关于javascript - 使用.attrTween方法延迟动画弧,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47681133/