D3.js timer()サンプル 棒グラフが サイン波で動きます | いまのままぢゃダメだ! ・・たぶん。

D3.js timer()サンプル 棒グラフが サイン波で動きます


D3.jsのアニメーションの練習に作ってみました。
下の図のようなサイン波を描く棒グラフが動きます。

d3.timer()を使用して、繰り返しの動作を実現しています。




もっと上手くできるような気がします。。

動きは、こんなカンジになります。 → サンプルを動かす

 ※ SVG版も作りました! → この記事です。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>D3.js サイン波 サンプル</title>
  <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
  <style type="text/css">

    div.bar {
      display: inline-block;
      width: 20px;
      height: 100px;
      margin-right: 2px;
      background-color: mediumspringgreen;
    }
  </style>
</head>
<body>
<script type="text/javascript">
  var dataset = [ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90,
      100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
      210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310,
      320, 330, 340, 350, 360 ];
  var a = 0;

  d3.select("body").selectAll("div")
    .data(dataset)
    .enter()
    .append("div")
    .attr("class", "bar")
    .style("height", function(d) {
      var barHeight = Math.sin( d / 180 * Math.PI ) * 100 + 100;
      return barHeight + "px";
    });

 d3.timer(function(){
   d3.select("body").selectAll("div")
     .data(dataset)
     .attr("class", "bar")
     .style("height", function(d) {
       var barHeight = Math.sin( ( d + a) / 180 * Math.PI ) * 100 + 100;
       return barHeight + "px";
     });
   a = a + .7;
   if ( a >= 360 ) { a = a - 360; }
 });
</script>
</body>
</html>





インタラクティブ・データビジュアライゼーション ―D3.jsによるデータの可視化
Scott Murray
出版社: オライリージャパン