gpt4 book ai didi

javascript - 在 d3 中链接转换的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-30 17:14:49 26 4
gpt4 key购买 nike

受此启发 other question ,我创建了一个动画 ( jsfiddle ) 来绘制一个圆,然后是一条将它连接到另一个圆的线。我读到 D3 v3 不需要监听 end 事件以进行链式转换。

enter image description here

下面的代码可以工作,但我应该如何重构它才能使其不使用 end 事件?

var margin = {top: 40, bottom: 40, left: 40, right: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.bottom - margin.top;

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var t0 = svg.append("circle")
.attr("r", 0)
.attr("cx", 40)
.attr("cy", 40)
.attr("class", "point")
.transition()
.duration(500)
.attr("r", 4);

var t1 = t0.each("end", function(){
var t2 = svg.append("path")
.style("stroke", "#000")
.style("stroke-width", 2)
.style("fill", "none")
.attr("d", "M40,40L40,40")
.transition()
.ease("linear")
.duration(500)
.attr("d", "M40,40L80,80");

t2.each("end", function(){
svg.append("circle")
.attr("r", 1)
.attr("cx", 80)
.attr("cy", 80)
.attr("class", "point")
.transition()
.duration(500)
.attr("r", 4);
});
});

最佳答案

好的,感谢评论,我意识到我可以做到这一点:

  • 附加第一项并使用 t0 = svg.transition() 创建第一个转换,
  • 附加第二个项目并创建第二个转换(将在 t0 结束后触发)t1 = t0.transition()
  • 对第三项重复 t2 = t1.transition()

请注意,如果要更改每个过渡的持续时间,必须在定义时完成。这是错误的:

var t1 = t0.transition()
.ease("linear");
t1.select("path.line")
.duration(500)
.attr("d", "M40,40L80,80");

应该是:

var t1 = t0.transition()
.ease("linear");
.duration(500)
t1.select("path.line")
.attr("d", "M40,40L80,80");

这是最终代码(jsfiddle):

var margin = {top: 40, bottom: 40, left: 40, right: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.bottom - margin.top;

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("circle")
.attr("r", 0)
.attr("cx", 40)
.attr("cy", 40)
.attr("class", "point-start")

svg.append("path")
.style("stroke", "#000")
.style("stroke-width", 2)
.style("fill", "none")
.attr("class", "line")
.attr("d", "M40,40L40,40");

svg.append("circle")
.attr("r", 0)
.attr("cx", 80)
.attr("cy", 80)
.attr("class", "point-end")

var t0 = svg.transition()
.duration(100);

t0.select("circle.point-start")
.attr("r", 4);

var t1 = t0.transition()
.duration(500)
.ease("linear");
t1.select("path.line")
.attr("d", "M40,40L80,80");

var t2 = t1.transition()
.duration(100);
t2.select("circle.point-end")
.attr("r", 4);

关于javascript - 在 d3 中链接转换的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com