■ はじめに
https://dk521123.hatenablog.com/entry/2015/10/07/000426
の続き。 今回は、D3.jsでのアニメーション表示について扱う。
【1】関連するメソッド
1)transition()
* アニメーション開始 cf transition : 〔形や状態などが〕推移[移行]する、 移り変わり,移行,変遷,変化
2)duration()
* アニメーションにかかる時間 [ms]
3)ease()
* アニメーションの動きを変える
デモサイト
https://wizardace.com/d3-transition-ease/
https://observablehq.com/@d3/easing-animations
d3.select("circle") .transition() .duration(750) .ease(d3.easeBounceOut) .attr("cx", 500);
4)delay()
* 待機時間[ms]
5)each()
* transitionの最初と最後に処理を実行する
【2】使用上の注意
* アニメーションする際は、アニメーション前の設定値も 重要になってくる(each()を使った方がいい?)
例
以下の例だと、設定値を以下のようにしておくと、 棒グラフは下から上に伸びるような動きをする。 アニメーション前(★1) アニメーション後(★2) ------------------------------------------------------------------- 「高さ」を「0」 → 「高さ」を「グラフ値に沿った値」 「y軸位置」を「表示最大値」 → 「y軸位置」を「グラフ値に沿った値」
例1:棒グラフ
var barChart = svg.selectAll(".bar") .data(dataset) .enter() .append("rect") .attr("class", "bar") .attr("fill", function(d) { return d.graphColor; }) .attr("x", function(d) { return x(d.graphId); }) .attr("width", x.rangeBand()) .attr("height", 0) // ★1 アニメーション前の設定値★ .attr("y", function(d) { return height; }); // ★1 アニメーション前の設定値★ // アニメーション barChart.transition() .delay(function (d, i) { return i * 100; }) .duration(1000) .ease("bounce") // bounceの動きを指定する .attr("y", function(d) { return y(d.yVal); }) // ★2 設定値★ .attr("height", function(d) { return height - y(d.yVal); }); // ★2 設定値★
【3】サンプル
例1:円グラフ
g.append("path") .attr("d", arc) .style("fill", function(d) { return d.data.graphColor; }) // アニメーション効果 .transition() .duration(1000) // 1秒間でアニメーションさせる .attrTween("d", function(d){ var interpolate = d3.interpolate( { startAngle : 0, endAngle : 0 }, { startAngle : d.startAngle, endAngle : d.endAngle } ); return function(t){ return arc(interpolate(t)); } });
例2:折れ線グラフ
var totalLength = path.node().getTotalLength(); path.attr("stroke-dasharray", totalLength + " " + totalLength) .attr("stroke-dashoffset", totalLength) .transition() .duration(1000) // アニメーション速度 .ease("linear") .attr("stroke-dashoffset", 0);
参考文献
* よく書かれている
http://dataisfun.org/2014/05/14/?p=242
関連記事
D3.js ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2015/10/07/000426