gpt4 book ai didi

javascript - 了解为什么在 .attrTween 中使用三个嵌套函数

转载 作者:行者123 更新时间:2023-11-29 18:40:31 25 4
gpt4 key购买 nike

This Mike Bostock 的例子对我很有用。它显示了一个点沿着曲线闭合路径无限流动。代码非常简单,除了最后几行我不明白。我在下面写下相关代码:

transition();

function transition() {
circle.transition()
.duration(10000)
.attrTween("transform", translateAlong(path.node()))
.each("end", transition);
}

// Returns an attrTween for translating along the specified path element.
function translateAlong(path) {
var l = path.getTotalLength();
return function(d, i, a) {
return function(t) {
var p = path.getPointAtLength(t * l);
return "translate(" + p.x + "," + p.y + ")";
};
};
}

为什么会出现三个嵌套函数?我知道外层函数translateAlong应该返回一个t(时间)的函数,但是我不明白中间函数(d, i ,一)。我只测试过它不能被省略,但它的参数可以。

最佳答案

我们有 3 个函数。让我们命名它们的级别:

function translateAlong(path) {//1st level here
var l = path.getTotalLength();
return function(d, i, a) {//2nd level here
return function(t) {//3rd and last level
var p = path.getPointAtLength(t * l);
return "translate(" + p.x + "," + p.y + ")";
};
};
}

为了回答您的问题,了解这...非常重要

.attrTween("transform", translateAlong(path.node()))

... 将调用 translateAlong 立即 并获取其返回值。这是哪个:

function(d, i, a) {//2nd level here
return function(t) {//3rd and last level
var p = path.getPointAtLength(t * l);
return "translate(" + p.x + "," + p.y + ")";
};
};

现在,让我们转到 D3 v3 API (您链接中的版本)。它说:

transition.attrTween(name, tween)

Transitions the value of the attribute with the specified name according to the specified tween function. The starting and ending value of the transition are determined by tween; the tween function is invoked when the transition starts on each element, being passed the current datum d, the current index i and the current attribute value a, with the this context as the current DOM element. (emphasis mine)

正如您在我以粗体显示的部分中的参数名称所看到的(即使 Bostock 从不使用它们,这也解释了您的正确观察“它的参数可以[被省略]”) ,补间函数正是您要询问的函数:

return function(d, i, a) {//this is the tween
return function(t) {
var p = path.getPointAtLength(t * l);
return "translate(" + p.x + "," + p.y + ")";
};
};

值得一提的是,考虑到 JavaScript 闭包的工作方式,变量 l (var l = path.getTotalLength();) 可由补间函数访问。

关于javascript - 了解为什么在 .attrTween 中使用三个嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440953/

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