我一直在尝试复制 link 中存在的示例。所以我从两个圆圈开始,一个固定,一个旋转。但旋转圆会逐渐远离静止圆,有时还会落入静止圆。有人可以帮我解决这个问题吗?我在以下位置创建了代码的实时演示 link .下面分享的是完整代码。
// takes two points x1,y1,x2,y2 and return r and Θ
function coordinateToPolar(x1,y1,x2,y2){
polar={}
polar.r= Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2))
polar.theta=Math.atan2(y2-y1,x2-x1)
return polar;
}
function degreeToRadians(degree){
return (degree/180)*Math.PI;
}
function radiansToDegrees(rad){
return (rad/Math.PI)*180
}
// takes one point h,k the center of circle and r and Θ
function polarToCoordinate(r,theta,h,k){
point={}
point.x=h+r*Math.cos(theta);
point.y=k+r*Math.sin(theta);
return point;
}
//circle ds
function Circle(r,h,k) {
this.r=r;
this.h=h;
this.k=k;
}
/// Adjusting the geometric center
bufferX=250;
bufferY=250;
svg=d3.select("body").append("svg");
startX=200;
startY=200;
startR=150;
dsCircles=[];
// intiating prevR and lastR to 0
prevR=0;
lastR=0;
for(i=0;i<2;i++){
currR=startR>>(i*1);
dsCircles[i]=new Circle(currR, i==0?bufferX+prevR+currR: bufferX+ prevR+lastR+currR,bufferY+startY)
lastR=currR;
prevR +=currR;
}
svg.selectAll("circles").data(dsCircles).enter().append("circle").attr("id",function(d,i){return "circle"+(i+1)}).attr("r",function(d){ return d.r}).attr("cy",function(d){return d.k}).attr("cx",function(d){ return d.h});
window.setInterval(function interval(){
// static variable initiated only once
if(interval["itr"]==undefined){
// initializing iteration counter to 0
interval.itr=0;
// getting the polar coordinates of the circles with respect to geometric center
interval.theta=coordinateToPolar(dsCircles[0].h,dsCircles[0].k,dsCircles[1].h,dsCircles[1].k).theta;
interval.r=coordinateToPolar(dsCircles[0].h,dsCircles[0].k,dsCircles[1].h,dsCircles[1].k).r;
}
d3.select("#circle2").attr("cx",function(d){
// assigning new center x-coordinate
return polarToCoordinate(interval.r,interval.theta,dsCircles[0].h,dsCircles[0].k).x;
}).attr("cy",function(d){
// assigning new center y-coordinate
return polarToCoordinate(interval.r,interval.theta +.03,dsCircles[0].h,dsCircles[0].k).y;
});
d3.select("#circle2").attr("style",function(d){ return interval.itr%2==0?"stroke:red":"stroke:blue"; })
interval.itr++;
interval.theta +=.003
},10)
最佳答案
只需在此处删除 cy +.03
的 Angular 偏移:
attr("cy",function(d){
// assigning new center y-coordinate
return polarToCoordinate(interval.r,interval.theta +.03,
关于javascript - 分形螺旋图 : possible rounding errors in javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42746071/