javascript:chartjs

Chart.js - デザイナーと開発者向けのシンプルでありながら柔軟な JavaScript チャート

Getting Started | Chart.js
Chart.js の「はじめに」のように、HTML、JavaScript、CSS に分けて、JavaScript は const labels (ラベル定義)、const data (データ定義)、const config (設定)、const myChart (グラフ描画) に分けて記述する🤔

公式ドキュメント Responsive Charts | Chart.js より抜粋🤔

The following examples do not work:

  • <canvas height=“40vh” width=“80vw”>: invalid values, the canvas doesn't resize (example)
  • <canvas style=“height:40vh; width:80vw”>: invalid behavior, the canvas is resized but becomes blurry (example)
  • <canvas style=“margin: 0 auto;”>: invalid behavior, the canvas continually shrinks. Chart.js needs a dedicated container for each canvas and this styling should be applied there.

Important Note
Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size (example):

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
    <canvas id="chart"></canvas>
</div>

The chart can also be programmatically resized by modifying the container size:

chart.canvas.parentNode.style.height = '128px';
chart.canvas.parentNode.style.width = '128px';

Note that in order for the above code to correctly resize the chart height, the maintainAspectRatio option must also be set to false.

<canvas> を直接リサイズするのではなく、コンテナ <div class="chart-container"> に入れてコンテナをリサイズする🤔
optionsmaintainAspectRatio はデフォルトで true だが、これをキャンバスの縦横比を維持しないように false に設定する🤔
maintainAspectRatio: サイズ変更時に元のキャンバスの縦横比 (width/height) を維持します。
aspectRatio: キャンバスの縦横比 (width/height)。チャートの種類によりデフォルト 1 または 2。
HTML

  <div class="chart-container">
    <canvas id="myChart"></canvas>
  </div>

js

  const config = {
    options: {
      maintainAspectRatio: false,
    }
  }

css

.chart-container {
  position: relative;
  width: 200px;
  height: 400px
}

  • javascript/chartjs.txt
  • 最終更新: 2022/11/10 12:44
  • by ともやん