How to set a fixed size for canvas on chart.js?

by hal.littel , in category: HTML & CSS , 7 months ago

How to set a fixed size for canvas on chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , a month ago

@hal.littel 

To set a fixed size for a canvas in Chart.js, you can use CSS to define the width and height of the canvas element. Here's an example of how you can do this:

  1. Add a canvas element to your HTML file with an ID:
1
<canvas id="myChart"></canvas>


  1. Use CSS to define the width and height of the canvas element:
1
2
3
4
#myChart {
  width: 400px; /* Set the width to your desired fixed size */
  height: 400px; /* Set the height to your desired fixed size */
}


  1. Initialize your Chart.js chart using the canvas element ID:
1
2
3
4
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  // Add your chart configuration options here
});


With this approach, the canvas element will have a fixed size of 400x400 pixels, but you can adjust the width and height values in the CSS to set a different fixed size for your canvas.