Javascript 递归函数和这个D3.JS
我有一个点数组,Javascript 递归函数和这个D3.JS,javascript,d3.js,recursion,Javascript,D3.js,Recursion,我有一个点数组,point={x,y,nextPoint}。其目的是在每个点之间画一条线,并在其上移动一个圆。数组中最后一个点的nextPoint为空 通过调用点上的[点数]-1方法,我可以移动一个圆。这一点都不灵活,我想递归地做。我正在创建一个这样的圆: function addCercle() { var ret = svg.append("circle") //svg is declared before .attr("cx", points[0].x) // points =
point={x,y,nextPoint}
。其目的是在每个点之间画一条线,并在其上移动一个圆。数组中最后一个点的nextPoint
为空
通过调用点上的[点数]-1
方法,我可以移动一个圆。这一点都不灵活,我想递归地做。我正在创建一个这样的圆:
function addCercle() {
var ret = svg.append("circle") //svg is declared before
.attr("cx", points[0].x) // points = the array of points
.attr("cy", points[0].y)
.attr("r", "3%");
return ret;
}
不起作用的功能是:
function move(p) {
for (var i = 0; i < points.length-1; i++) {
p = d3.select(this)
.transition()
.duration(speed) //
.attr("cx", points[i].x)
.attr("cy", points[i].y);
}
}
有人能解释一下我在移动功能时需要改变什么吗?或者在调用中?如果要使
移动
函数递归,则需要从函数本身内部调用它。与往常一样,有很多方法可以实现这一点,但如果您有一个点数组,则可以传入点数组,也可以传入点数组中的当前位置。下面是一个示例,其中您传入一组点:
// p is the element being moved, points is the array of points
function move(p, points) {
if (points.length > 0) { // one point or more in the array => move the element
p.transition()
.duration(speed) //
.attr("cx", points[0].x)
.attr("cy", points[0].y)
// when the transition ends, call this function with the array of points minus the first point
.on('end', () => move(p, points.slice(1)));
}
}
const arrayOfPoints = [{x: 100, y: 200},{x: 200, y: 200}, {x: 300, y: 300}]
// call the function
move(circle, arrayOfPoints);
工作示例,其中我生成了一组点,然后沿这些点所描述的路径移动了一个圆:
var svg=d3.选择('svg'),
半径=100,
pts=d3.range(0,2*Math.PI,0.01*Math.PI)//注意:这将生成一个数组
.map(d=>d3.pointRadial(d,radius)),//数组;略有不同
//到您的数据结构
速度=50
函数地址(点){
var ret=svg
.append('g')
.attr('transform','translate(150150)'
.append(“circle”)//svg在
.attr(“cx”,points[0][0])//points=点的数组
.attr(“cy”,分数[0][1])
.attr(“r”,“3%”);
返回ret;
}
功能移动(p,点){
如果(点长度>0){
p、 过渡()
.持续时间(速度)//
.attr(“cx”,分数[0][0])
.attr(“cy”,分数[0][1])
.on('end',()=>move(p,points.slice(1));
}
}
var测试=附加成本(pts);
移动(测试,pts)代码>
这在您的范围内是什么?它不应该是d3。选择(p)
?如果我知道你想做的是“沿路径插值点”,这对我来说很好,但通过你的例子,我有这个错误d3。pointRadial不是一个函数,我如何修复它?这个函数应该做什么?它把一个角度和一个半径转换成笛卡尔坐标。你不应该需要它——我只是用它来生成一组点来演示递归函数。
// p is the element being moved, points is the array of points
function move(p, points) {
if (points.length > 0) { // one point or more in the array => move the element
p.transition()
.duration(speed) //
.attr("cx", points[0].x)
.attr("cy", points[0].y)
// when the transition ends, call this function with the array of points minus the first point
.on('end', () => move(p, points.slice(1)));
}
}
const arrayOfPoints = [{x: 100, y: 200},{x: 200, y: 200}, {x: 300, y: 300}]
// call the function
move(circle, arrayOfPoints);