javascript – 如何在d3.js中围绕中心旋转对象

我在d3.js中有两个简单的物体,它们应围绕视口的中心盘旋(就像围绕太阳的行星一样).

我是d3.js的新手,我知道我必须使用过渡但是因为行星必须一直循环而不仅仅是进入或退出我不知道在哪里以及如何设置过渡.

这是我目前的代码:

var planets = [
    {d:100,r:2},{d:150,r:4}
];

var w = 500,h = 400,svg,circle;

function init(){

    svg = d3.select("#drawArea").append("svg").attr({width: w,height: h});

    var center = {
        x: Math.floor(w/2),y: Math.floor(h/2)
    };

    svg.append('circle').attr({
        'cx': center.x,'cy': center.y,'r': 10,'class': 'sun'
    });

    circle = svg.selectAll(".planet")
        .data(planets)
        .enter()
            .append("circle")
                .attr("class","planet")
                .attr("r",function(s){return s.r});

    circle.attr({
        // distance from the center
        'cx': function(s){ return center.x - s.d; },// center of the screen
        'cy': function(s){ return center.y; }
    });

}

这里有一个jsfiddle玩.

解决方法

你需要:

>将你的行星放在以g为中心的g组中
>创建一个用于旋转组的d3.timer.

有关使用d3.timer的示例,请参阅Mike Bostocks Epicyclic Gearing示例.使用这个例子,我把类似于你问的东西放在一起:http://bl.ocks.org/4953593

示例的核心:

var w = 800,h = 800;
  var t0 = Date.now();

  var planets = [
    { R: 300,r:  5,speed: 5,phi0: 90},{ R: 150,r: 10,speed: 2,phi0: 190}
  ];


  var svg = d3.select("#planetarium").insert("svg")
    .attr("width",w).attr("height",h);

  svg.append("circle").attr("r",20).attr("cx",w/2)
    .attr("cy",h/2).attr("class","sun")

  var container = svg.append("g")
    .attr("transform","translate(" + w/2 + "," + h/2 + ")")

  container.selectAll("g.planet").data(planets).enter().append("g")
    .attr("class","planet").each(function(d,i) {
      d3.select(this).append("circle").attr("class","orbit")
        .attr("r",d.R);
      d3.select(this).append("circle").attr("r",d.r).attr("cx",d.R)
        .attr("cy",0).attr("class","planet");
    });

  d3.timer(function() {
    var delta = (Date.now() - t0);
    svg.selectAll(".planet").attr("transform",function(d) {
      return "rotate(" + d.phi0 + delta * d.speed/200 + ")";
    });
  });

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小