Chartjs-Bar graph not taking 100%

0👍

Your code and configuration looks correct and works ( demo seen below ) but if you want to be on the save side yo can add the properties max:100 to the y axis, this could fix the hight issue.

Here the demo:

const data = {
    labels: [2022],
    datasets: [{
          label: 'Legend 1',
          data: [50],
          backgroundColor: '#fdfd96', // yellow
        },
        {
          label: 'Legend 2',
          data: [50],
          backgroundColor: '#77b5fe', // blue
        },],
};

const config = {
    type: 'bar',
    data: data,
    options: {
        maintainAspectRatio: false,
        animation: {
            onComplete: function () {
                let img = document.createElement('img')
                let url = this.toBase64Image()
                img.src = url
                document.querySelector('#imagePreview').append(img);
            }
        },
        scales: {
        x: {
          stacked: true,
        },
        y: {
          stacked: true,
          max:100
        },
    }}
};

var cart = new Chart(
    document.getElementById('chart'),
    config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>  

<div class="chart" style="height:184px; width:350px;">
    <canvas  id="chart" ></canvas>
</div>
<b> preview Image </b>
<div id="imagePreview"></div>

Update screenshot of result:

screenshot from snippet result

Update:

After testing the assumtion must be, that the save function is defective or there is some sort of race condition with a different chart. Since createing a image onComplete creates a correct images, in the updated demo.

I’m assuming the wrong visuals have to to with the animation, not being finished when the image is created, if this is so, one could workaround this fact (or just to test the theory), with using a timeout for creating the image, something like this

onComplete: function () {
    setTimeout( () => {
        saveChartAsImage(
            this.toBase64Image(),
            currentYear,
            companyId,
            'actif',
            manualMode,
         );
    }, 1000); // <-- One Second should be enough for the animation to end
}

Leave a comment