チャートライブラリの使い方(7)「グラフを動かす」
hifiveのチャートライブラリの使い方を紹介します。今回はグラフを移動させるデモです。
ベースはチャートライブラリの使い方(1)「基本編」 | hifive開発者ブログのグラフになります。
実行しているところは下記の通りです。こちらのURLにてサンプルを試せます。
HTMLのボタンを追加
HTMLを次のように修正します。進む、戻るのボタンを追加します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="chart"></div> | |
<p> | |
<button id="go"> | |
進む | |
</button> | |
<button id="back"> | |
戻る | |
</button> | |
</p> |
ダミーデータ生成部分を修正
任意のデータ数生成できるように修正します。これは実運用時には不要でしょう。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// size 変数を追加 | |
function createChartDummyData(median, vibration, size) { | |
size = size || 200; // デフォルトは200 | |
var ret = []; | |
for (var i = 0; i < size; i++) { | |
ret.push({ | |
val: median + (Math.random() – 0.5) * vibration * 2 | |
}); | |
} | |
return ret; | |
} |
進むボタンを押した時の処理
進むボタンを押した時には、グラフを1つ進めます。その際、一番右端かどうかの判定を行って、端であればデータを追加します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"#go click": function() { | |
var movedNum = this._chartController.go(1); | |
if (movedNum === 1) { | |
return; | |
} | |
// 追加データ生成 | |
addData = [{name: 'series_1', data: createChartDummyData(400, 100, 1)[0]}]; | |
// データ追加 | |
this._chartController.addData(addData); | |
}, |
戻るボタンを押した時の処理
戻るボタンを押した時にはグラフを一つ戻します。この時、左端であればグラフは動きません。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"#back click": function() { | |
this._chartController.back(1); | |
}, |
注意点としてはデータを追加する際にデータ系列名(name)を初期表示時と同じにしておくということです。
例えばこの進むボタンを押した時の処理をsetIntervalで繰り返すようにすると刻々と描画が更新されるグラフができあがります。
ぜひサンプルをお試しください!
コメントは受け付けていません。