0
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 1 year has passed since last update.

Chartjsで座標を表示させる方法

Last updated at Posted at 2021-11-24

##chartjsで座標を表示させる方法
まずchartjsのドキュメントからテンプレートを使用する.
https://www.chartjs.org/docs/latest/
この中のチャートタイプに散布図のテンプレコードがある.
これを使用して以下のchart_init.jsのコードを書く

const ctx = document.getElementById('myChart').getContext('2d');
const input_data = [];

const data = {
    datasets: [
      {
        label: 'Dataset 1',
        data: input_data,
        fill: false,
        borderColor: 'rgb(0, 0, 0)',
        backgroundColor: 'rgb(100, 255, 100)',
      }
    ]
  };

const config = {
    type: 'scatter',
    data: data,
    options: {
        elements: {
            line: {
                tension: 10
            },
        },
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'POSITION'
            }
        },
        scales: {
            x: {
                min: 0,
                max: 100,
            },
            y: {
                min: 0,
                max: 100,
            }
        }
    },
};

const myChart = new Chart(ctx, config);

次にmain.jsのコードを書く

function pushPosition(x, y) {
    input_data.push({'x':x, 'y':y});
    myChart.update();
    return true;
}

//sample
for (let i = 0; i < 300; i++) {
    pushPosition(i/10, i/10);
}

次にHTMLの設定を行う

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="myChart" width="400" height="400"></canvas>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.0/dist/chart.min.js"></script>

    <script src="./chart_init.js"></script>
    <script src="./main.js"></script>
</body>
</html>

これでHTMLのファイルを起動するし, pushPosition(x, y)でxとyに表示したい数値をconsoleに入力することによって以下のように表示することができる.

スクリーンショット 2021-11-17 21.48.13.png

0
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
0
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?