gpt4 book ai didi

javascript - d3轨道使用变换旋转

转载 作者:行者123 更新时间:2023-11-29 10:45:04 25 4
gpt4 key购买 nike

我想知道我的数学问题在哪里,或者是否有更好的方法来实现我试图用 d3 实现的目标。本质上,我有一个给定半径的旋转圆,我想围绕它旋转任意数量的较小形状,类似于这个轨道示例 here .但问题是我不想使用计时器,因为我的场景涉及沿大圆的半径旋转小圆,每个小圆之间的旋转 Angular 相等。因此,例如,第一个圆将沿半径旋转 315 度,下一个圆将旋转 270 度,依此类推,直到每个圆距离相等。这是假设我有 8 个较小的圆圈,所以它们之间的 Angular 为 45 度。问题是调用旋转 Angular 大于 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 : fiddle

最佳答案

类似于动画饼图(参见例如 here ),您需要一个自定义补间函数——默认插值并不适合任何径向。幸运的是,这相对简单,您只需告诉 D3 如何对 Angular 进行插值,在本例中就是一个简单的数字插值。

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 .

关于javascript - d3轨道使用变换旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21052888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com