3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Chart.jsで円グラフにonclickをつける

Last updated at Posted at 2018-06-14

概要

クリックされた要素ごとに違う動きを付けたかった際に苦労したのでメモ代わりに
(初学者なので間違い等あるかもしれません)

サンプルコード

sample.html
<!DOCTYPE html>

<head>
    <title>Pie Chart</title>
</head>

<body>
    <canvas id='myChart'></canvas>

    <script src='http://code.jquery.com/jquery-3.3.1.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js'></script>
    <script src='sample.js'></script>
</body>

</html>
sample.js
let myChart = new Chart(ctx, {
    type: 'pie',
    data: data = {
        labels: ['Red', 'Yellow', 'Blue'],
        datasets: [{
            data: [10, 20, 30],
            backgroundColor: ['#FF0000', '#00FF00', '#0000FF']
        }],
    },
});


$('#myChart').on('click', (evt) => {
    // クリックされたアイテムの取得
    const activePoints = myChart.getElementsAtEvent(evt);

    if (activePoints.length > 0) {
        // クリックされた配列の番号
        const clickedElementindex = activePoints[0]['_index'];

        // クリックされた要素の内容
        const label = myChart.data.labels[clickedElementindex];

        if (label === 'Red') {
            console.log('Red');
        }
        else if (label === 'Yellow') {
            console.log('Yellow');
        }
        else if (label === 'Blue') {
            console.log('Blue');
        }
    }
});

結果

image.png

まとめ

labelをif文で判定しているのでやり方としてあんまり美しくないかなぁと思ったり。。。
押された際にmyChart.update()でグラフを更新したりすれば表現の幅が広がりそうですね!

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?