How to resize canvas with Chart.js and JavaScript?

To resize a canvas containing a chart created with Chart.js, we can use the resize method provided by Chart.js.

To do this, we write:

// Get the canvas element
var canvas = document.getElementById('myChart');

// Get the context of the canvas element
var ctx = canvas.getContext('2d');

// Create your chart
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My Dataset',
            data: [65, 59, 80, 81, 56, 55, 40]
        }]
    },
    options: {
        // Your chart options here
    }
});

// Function to resize the canvas
function resizeCanvas() {
    // Get the current size of the canvas
    var currentWidth = canvas.clientWidth;
    var currentHeight = canvas.clientHeight;

    // Check if the canvas is not already the same size
    if (canvas.width !== currentWidth || canvas.height !== currentHeight) {
        // Set the canvas to the new size
        canvas.width = currentWidth;
        canvas.height = currentHeight;

        // Redraw the chart
        myChart.resize();
    }
}

// Call the resizeCanvas function whenever the window is resized
window.addEventListener('resize', resizeCanvas);

// Call the resizeCanvas function once to initially resize the canvas
resizeCanvas();

This code creates a Chart.js chart on a canvas element with the ID myChart. The resizeCanvas function resizes the canvas to match its current size whenever the window is resized, and then calls the resize method of the chart to update the chart’s size accordingly.