d3轨道使用变换旋转

时间:2014-01-10 19:33:16

标签: javascript animation d3.js

我想知道我的数学在哪里或者是否有更好的方法来实现我想用d3完成的事情。基本上我有一个给定半径的旋转圆,我希望旋转任意数量的较小的形状,类似于这个轨道示例here。但问题是我不想使用计时器,因为我的方案涉及沿着较大圆的半径旋转小圆圈,每个圆圈之间具有相等的旋转角度。因此,例如,第一个圆圈将沿着半径旋转到315度,接下来旋转到270度,依此类推,直到每个圆圈距离相等。这假设我有8个较小的圆圈,所以它们之间的角度是45度。问题是调用旋转角度大于180度会导致轨道朝错误的方向发生。

var dataset = [1, 2, 3, 4, 5, 6, 7, 8];

var width = 600,
    height = 600,
    rad = Math.PI / 180,
    layerRadius = 10,
    radius = width / 2,
    step = 360 / dataset.length,
    svg = d3.select('#ecosystem')
        .attr('width', width)
        .attr('height', height);

var layers = svg.selectAll('g')
    .data(dataset)
    .enter()
    .append('g')
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

layers.append('circle')
    .attr('class', 'planet')
    .attr('cx', 0)
    .attr('cy', -height / 2)
    .attr('r', layerRadius)
    .attr('fill', 'none')
    .style({
    'stroke': 'black',
    'stroke-width': 1
});

svg.selectAll('.planet')
    .transition()
    .duration(600)
    .delay(function (d, i) {
    return i * 120;
})
.ease('cubic')
.attr("transform", function (d, i) {
    //angle should be 360 - step * (i + 1);
    console.log(360 - step * (i + 1));
    var angle = 360 - step * (i + 1);
    return "rotate(" + angle + ")";
});

//circle of rotation    
var c = svg.append('circle')
    .attr('cx', width / 2)
    .attr('cy', height / 2)
    .attr('r', radius)
    .attr('fill', 'none')
    .style({
    'stroke': 'black',
    'stroke-width': 1
});

//center point
var cp = svg.append('circle')
    .attr('cx', width / 2)
    .attr('cy', height / 2)
    .attr('r', 1)
    .attr('fill', 'none')
    .style({
    'stroke': 'black',
    'stroke-width': 1
});

这是小提琴: fiddle

1 个答案:

答案 0 :(得分:3)

与饼图动画类似(参见例如here),您需要一个自定义补间函数 - 默认插值并不适合任何径向。幸运的是,这是相对简单的,你只需要告诉D3如何插入角度,在这种情况下是一个简单的数字插值。

function angleTween(d, i) {
            var angle = 360 - ((i+1)*20);
            var i = d3.interpolate(0, angle);
            return function(t) {
                return "rotate(" + i(t) + ")";
            };
        }

然后,不要直接指定transform,而是给它这个函数:

.attrTween("transform", angleTween);

完整演示here

相关问题