[Chartjs]-Resizing chart before downloading as image

1👍

Here’s how I solved the problem. I’m sure there’s a better solution, but it does the job:

var button; // link to download chart
var canvas; // the chart canvas to download

button.addEventListener('click', _ => {
        let resized = adjustCanvasWidth(canvas);
        setTimeout(_ => {
            canvas.toBlob(blob => {
                    const img = URL.createObjectURL(blob);
                    const downloadLink = document.createElement('a');
                    downloadLink.href = img;
                    downloadLink.download = CHARTFILENAME + '.png';
                    downloadLink.click();

                    if(resized) {
                        canvas.parentElement.style.width = 'auto';
                        resizeChart(canvas);
                    }
            });
        }, 1000);
});

function adjustCanvasWidth(canvas) {
    let maxWidth = Math.round(canvas.clientHeight * 16 / 9);
    if(canvas.parentElement.clientWidth > maxWidth) {
        canvas.parentElement.style.width = maxWidth + 'px';
        return resizeChart(canvas);
    }
}

function resizeChart(canvas) {
    let charts = Object.values(Chart.instances).filter(chart => {
        return chart.canvas == canvas;
    });
    if(charts.length == 1) {
        let chart = charts[0];
        chart.resize();
        return true;
    }
}

Leave a comment