not good but great

プログラミング、アート、映画・本の感想について書きます。

Chart.jsを使って円グラフをアニメーションさせてみた

綺麗なチャートが作れる

Chart.jsはCanvasにチャートを描画できるライブラリです。アニメーションもできて、デザインを工夫すれば、おしゃれな図を作成することができます。動きや配色によって、チャートのわかりやすさは大きく変わると思うので、このようなライブラリはとても意義のあるものだと感じます。

Chart.js | Open source HTML5 Charts for your website
http://startapp.jp/2013/07/21/how-to-create-flat-chart.html
DevExtreme Demos: JavaScript UI Widgets by DevExpress

demo


チャートがアニメーションする様子を、アニメーション時間を変えてわかるように表示させてみました。モバイルでは重いので、PCで見ることをおすすめします。Canvasをたくさん生成させているからです・・・(他に方法が思いつかなかった泣)。

Chart.jsの使い方

使い方はドキュメントを見るのが一番良いと思います。
Chart.js | Documentation

ライブラリを読み込む

<script src="Chart.js"></script>

Canvasを定義

<canvas id="myChart" width="400" height="400"></canvas>

チャートを描画

var ctx = $("#myChart" + i).get(0).getContext("2d"),//Canvasのコンテキスト取得
var NewChart = new Chart(ctx);//チャートを生成

//円グラフを描画
myNewChart.Pie(data,options);

jQueryで書くと上のようになります。

チャートの詳細を定義

チャートのデータ

//円グラフのデータ
var data = [
	{
		value: 30,
		color:"#CCF600"
	},
	{
		value : 50,
		color : "#67E300"
	},
	{
		value : 100,
		color : "#FFE800"
	}			
];

チャートのデータは配列で定義します。円グラフの場合は上のように、値と色を決めます。折れ線グラフの場合は、ポイントの色・大きさ、線の色・太さ、横軸の指標を決めることができます。


チャートのスタイル

//円グラフのスタイル
var options = {
	//Boolean - Whether we should show a stroke on each segment
	segmentShowStroke : true,
	
	//String - The colour of each segment stroke
	segmentStrokeColor : "#fff",
	
	//Number - The width of each segment stroke
	segmentStrokeWidth : 2,
	
	//Boolean - Whether we should animate the chart	
	animation : true,
	
	//Number - Amount of animation steps
	animationSteps : 100,
	
	//String - Animation easing effect
	animationEasing : "easeOutBounce",
	
	//Boolean - Whether we animate the rotation of the Pie
	animateRotate : true,

	//Boolean - Whether we animate scaling the Pie from the centre
	animateScale : false,
	
	//Function - Will fire on animation completion.
	onAnimationComplete : null
};

スタイルはオブジェクトで定義します。ここではアニメーションさせたいので「animation : true,」にしています。

//アニメーション時間を調節
options.animationSteps = 30 + 5 * i;
//円グラフを描画
myNewChart.Pie(data,options);

今回のようにずらしてアニメーションさせたい場合は、描画の前に、オブジェクトの変数を上書きさせればよいです。