所以我已经用 D3.js 搞了几天,我有了基本的圆生成/动画(充当气泡),我想知道如何为 x 轴上的圆制作动画,所以随着旅行/过渡到页面顶部,它们会前后摆动。当前动画可以在chrisrjones.com/bubbles-v1.html观看。
最佳答案
解决方案演示:
注意不对称:
http://jsfiddle.net/blakedietz/R5cRK/1/embedded/result/
方法:
- 确定一个可以正确模拟您想要的运动的数学函数。
- 在这种情况下,我们需要一个正弦 波。我们可以修改每个气泡特征的各个方面,为每个气泡提供独特的运动模式。
- 利用解决此问题所需的关键概念构建或找到解决方案。
- 我喜欢在 bl.ocks.org/mbostock 上搜索包含我正在尝试解决的问题的基础部分的示例。在网站上我找到了这个例子:http://bl.ocks.org/mbostock/1371412
- 修改给定的示例以更类似地反射(reflect)指定的结果。
解决方案:
这是一个解决方案的快速演示。我会回到这个给你一个完整的演练。可以进行修改以使每个气泡的气泡位置和大小以及摆动随机/半唯一。
w = 960,
h = 500;
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
var circle = svg.selectAll("circle")
.data(d3.range(70).map(function(datum,interval) {
return {
x: interval*20,
y: 0,
dx: 5,
dy: -3 * (Math.random()+1),
mu: Math.random()*2
};
}))
.enter().append("svg:circle")
.attr("r", 2.5)
.attr("fill","blue")
.attr("opacity",".5");
var text = svg.append("svg:text")
.attr("x", 20)
.attr("y", 20);
var start = Date.now(),
frames = 0;
d3.timer(function()
{
// Update the FPS meter.
var now = Date.now(), duration = now - start;
text.text(~~(++frames * 1000 / duration));
if (duration >= 1000) frames = 0, start = now;
// Update the circle positions.
circle
.attr("cx", function(d) { d.x += Math.random()*3*Math.sin(Math.random()*3*d.x + Math.random()*10); if (d.x > w) d.x -= w; else if (d.x < 0) d.x += w; return d.x; })
.attr("cy", function(d) { d.y += d.dy ; if (d.y > h) d.y -= h; else if (d.y < 0) d.y += h; return d.y; })
.attr("r",function(d)
{
return (d.y < 100) ? d3.select(this).attr("r") : d.mu*500/d.y;
});
});
关于javascript - 使用 D3.js 制作圆圈动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20725548/