Web API的なアレで、DBから取ってきたデータをChart.jsで描画しようと思ったのだけどJSON書いてるとなんか混乱してきたので、APIが返すJSONをそのままChart.jsの形式にしてしまった。あんまり良くない気もするけど、どうなんだろなぁ。
最初C#で書いていたのだけど色々あってPHP。ASP.NETはまったく触ったことなかったのだけれど、ほとんどコードを書かずに済むのでこっちも楽そうです。
こういうクラスを作ってから
// sample.php
<?php
$chart = new Chart("bar");
$chart->data->labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
$ds = new DataSet();
for ($i = 0; $i < 12; $i++) $ds->data[] = rand(0, 100);
$chart->data->addDataSet($ds);
echo json_encode($chart);
?>
こんなページを作って
<html>
<head>
<script src="Chart.bundle.min.js"></script>
<script>
window.onload = function() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'sample.php', true);
xhr.responseType = 'json';
xhr.onload = function(e) {
var ctx = document.getElementById('canvas').getContext('2d');
new Chart(ctx, xhr.response);
}
xhr.send();
}
</script>
</head>
<body>
<canvas width="500" height="500" class="chartjs-render-monitor" id="canvas"></canvas>
</body>
</html>
というような感じでそのまま突っ込むとチャートが出てきます。
Chart.jsはコールバック関数を設定することもできますが、PHPでJSONを組み立てちゃうとそのあたりが利用できないのが結構大きなデメリットでしょうか。
window.onload = function() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'sample.php', true);
xhr.responseType = 'json';
xhr.onload = function(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var data = xhr.response;
var scales = {xAxes: [{
type: 'category',
ticks: {
maxRotation: 0,
callback: function(value, index, values) { return [value, (index+1) + "月"]; }
}
}]};
data.options["scales"] = scales;
new Chart(ctx, data);
}
xhr.send();
}
みたいな感じで無理矢理追加することはできますが…。