How to get the actual chart width and height in chart.js?

Member

by mac , in category: Javascript , 9 months ago

How to get the actual chart width and height in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 9 months ago

@mac 

To get the actual width and height of a chart in Chart.js, you can use the chart.canvas property to access the canvas element that the chart is drawn on. You can then use the clientWidth and clientHeight properties of the canvas element to get the actual width and height of the chart.


Here is an example of how you can get the actual width and height of a chart in Chart.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    }
});

var chartWidth = myChart.canvas.clientWidth;
var chartHeight = myChart.canvas.clientHeight;

console.log('Chart width: ' + chartWidth);
console.log('Chart height: ' + chartHeight);


In this example, we first create a new Chart instance and store it in the myChart variable. We then access the canvas element of the chart using myChart.canvas and get its clientWidth and clientHeight properties to get the actual width and height of the chart. Finally, we log the chart width and height to the console.