d3轨道使用transform rotate

3
我想知道我的数学哪里出了差错,或者是否有更好的方法来实现我尝试使用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个回答

3

与制作饼图的动画类似(例如,参见此处),您需要自定义缓动函数,因为默认的插值并不适用于任何径向动画。幸运的是,这相对简单,只需告诉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);

完整演示在这里


非常感谢!因此,Tween 可以在给定的属性上运行,并且插值函数会估计每个 Tween 的 x、y 坐标,或者对于给定属性的起始和结束点是什么。在我的情况下,开始角度为 0,最终角度是什么? - swallace
是的,除了它是两个值之间的简单插值(例如,使用0.5调用它会给您中点)。 tween函数的目的是告诉D3如何插值不明显的东西。例如,在“rotate(0)”和“rotate(180)”之间进行插值(作为字符串),这不是显然的。该tween函数仅设置单个值,即旋转角度。 - Lars Kotthoff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接