3

Set Chart Size with ChartJS

 2 years ago
source link: https://masteringjs.io/tutorials/chartjs/size
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Set Chart Size with ChartJS

Mar 25, 2022

To set the chart size in ChartJS, we recommend using the responsive option, which makes the Chart fill its container. You must wrap the chart canvas tag in a div in order for responsive to take effect. You cannot set the canvas element size directly with responsive.

Below is a chart that fills its container, which happens to be the exact width of the text container for Mastering JS.

Below is the HTML for the above chart.

<style>
  #chart-wrapper {
    display: inline-block;
    position: relative;
    width: 100%;
  }
</style>
<div id="chart-wrapper">
  <canvas id="chart"></canvas>
</div>

Below is the JavaScript for the chart:

const ctx = document.getElementById('chart').getContext('2d');
const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C'],
    datasets: [{
      label: 'Easy as',
      data: [1, 2, 3],
    }],
  },
  options: {
    responsive: true
  }
});


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK