gpt4 book ai didi

javascript - D3 : attrTween not working

转载 作者:行者123 更新时间:2023-11-30 15:07:55 24 4
gpt4 key购买 nike

我正在基于示例 here 在 d3 v3 中创建旭日形.我无法理解为什么 attrTween() 在以下情况下不起作用。

path.transition()
.duration(750)
.attrTween("d", function(d) {
var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
yd = d3.interpolate(y.domain(), [d.y, 1]),
yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
return function(d, i) {
var p = i
? function(t) { return arc(d); }
: function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return arc(d); };
return p
};
})

单击任何圆弧时出现以下错误。

Error: attribute d: Expected moveto path command ('M' or 'm'), "function (t) { x…".

但是,如下定义函数 arcTween() 并像这样调用 .attrTween("d", arcTween(d)) 工作正常。

function arcTween(d) {
var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
yd = d3.interpolate(y.domain(), [d.y, 1]),
yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
return function(d, i) {
return i
? function(t) { return arc(d); }
: function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t));return arc(d); };
};
}

最佳答案

工作代码使用函数声明来定义 function arcTween(d) { }。在 .attrTween("d", arcTween(d)) 中使用此函数将实际执行从封闭函数 click(d ),这是绑定(bind)到用户点击的元素的数据。此调用用于捕获/关闭内插器 xdydyr 中的值 d,反过来在返回的内部函数中使用。此返回函数是由 .attrTween() 执行以返回用于转换的插值器的函数。

在您的代码中,在尝试内联函数声明时,您错过了上面提到的对外部函数的调用。因此,您最终会得到一个无效的返回值,因为您的函数嵌套得太深了。

但是,有一个简单的补救措施可以使您的代码正常工作:只需在内联函数之后添加一个 (d) 即可像以前的代码一样执行它。

function click(d) {             // This d is what needs to be captured

path.transition()
.duration(750)
.attrTween("d", function(d) {
// var... // This is where the outer d is closed over/captured
return function(d, i) { // This is another d not to be confused with the outer one
// ...
};
}(d)) // This will execute the function passing in click's d

}

查看更新后的 Plunk用于工作演示。

关于javascript - D3 : attrTween not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45487702/

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