Which scenarios might make Chart.js's canvas element resize?

đź‘Ť:0

As you’ve discovered, ChartJS resizes your canvas as it feels necessary. It might change the width, height, both or neither so the shape of the final canvas is unpredictable.

One option you might set to limit resizing is:

responsive: false,

I guess the best you can do is draw the ChartJS canvas to another canvas with your desired size.

Here’s a function that will let you draw the ChartJS canvas to the new canvas without causing the chart to be cropped in the process. Warning–untested code that may need tweeking!

// create a new canvas of a specified size
function resize(chartCanvas,newWidth,newHeight){
    var newCanvas=document.createElement('canvas');
    var newCtx=newCanvas.getContext('2d');
    var cw=newCanvas.width=newWidth;
    var ch=newCanvas.height=newHeight;
    var iw=chartCanvas.width;
    var ih=chartCanvas.height;
    var scale=scalePreserveAspectRatio(iw,ih,cw,ch);
    newCtx.drawImage(chartCanvas,0,0,iw,ih,0,0,iw*scale,ih*scale);
    return(newCanvas);
}

// calculate a scaling factor that preserves
// the original aspect ratio
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
    return(Math.min((maxW/imgW),(maxH/imgH)));
}

Leave a comment