使用D3.js动画圆圈

时间:2013-12-22 02:12:10

标签: javascript animation d3.js

所以我一直在玩D3.js几天,我有基本的圆圈生成/动画(充当气泡),我想知道如何在x axsis上为圆圈设置动画,所以它们随着旅行/过渡到页面顶部而摆动。可以在chrisrjones.com/bubbles-v1.html

查看当前动画

2 个答案:

答案 0 :(得分:8)

解决方案演示:

注意缺乏对称性:

http://jsfiddle.net/blakedietz/R5cRK/1/embedded/result/

<强>方法

  • 确定一个能够正确模拟所需运动的数学函数。
    • 在这种情况下,我们想要一个正弦波。我们可以修改每个气泡特征的各个方面,为每个气泡提供独特的运动模式。
  • 构建或找到利用此问题所需的关键概念的解决方案。
    • 我喜欢在bl.ocks.org/mbostock上搜索那些具有我试图解决的问题基础部分的例子。在网站上我找到了这个例子:http://bl.ocks.org/mbostock/1371412
    • 修改给定示例以更类似地镜像指定的结果。

<强>解决方案:

以下是解决方案的快速演示。我会回到这里给你一个完整的步骤。可以进行修改以使气泡放置和尺寸调整以及每个气泡摆动随机/半独特。

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;
      });
});

答案 1 :(得分:2)

您可以使用cx var circlesTransition = d3.selectAll("circle") .transition() .duration(5000) .attr("cy", "0") .attrTween('cx', function (d, i, a) { return function (t) { // Add salt, pepper and constants as per your taste return a + (Math.random() - 0.5) * 10; }; }); 来执行此操作:

{{1}}
相关问题