[Chartjs]-How to Minimise the Size of the Dynamically Loaded Polar Area Chart of ChartJS

2👍

CharJS resize/render canvas relative to it’s parent container. So if you want to decrease the size of the canvas then you just need to decrease the size of it’s container.

for more info please look for this documentation guide for responsiveness

Here is the modified code (modification is only in .html file)

const chartData = [
        [10, 20, 30],
        [20, 30, 40],
        [30, 40, 50]
    ];

    // Loop through the chart data and create a chart for each
    for (let i = 0; i < chartData.length; i++) {
        debugger;
        // Create a canvas element with a unique ID
        const canvas = document.createElement('canvas');
        canvas.id = `chart-${i}`;
        canvas.style.width = '100px';
        canvas.style.height = '100px';

        // Add the canvas to the page
        const chartContainer = document.getElementById('chart-containerpolar');
        chartContainer.appendChild(canvas);

        // Create a new Chart object for the canvas
        const chart = new Chart(canvas, {
            type: 'polarArea',
            data: {
                datasets: [{
                    data: chartData[i],
                    backgroundColor: [
                        "rgb(68, 114, 197)",
                        "rgb(255, 191, 0)",
                        "rgb(104, 163, 68)"
                        //'rgba(75, 192, 192, 0.2)',
                        //'rgba(153, 102, 255, 0.2)',
                        //'rgba(255, 159, 64, 0.2)'
                    ],
                }],
                labels: ['Part1', 'Part2', 'Part3']
            },
            options: {
                responsive: true,
               /* maintainAspectRatio: false,*/
                scale: {
                    ticks: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div id="chart-containerpolar" style="width: 300px; height: 300px"></div>

<!-- You need to make sure that container has the proper size and width so that chart canvas can take the size relatively to it's parent -->

Leave a comment