7

I'm using Chart.js to create pie charts. I need each chart to be 76x76px. Unfortunately, the rendered chart is always a bit smaller than the size if the wrapping div and the canvas itself.

If you inspect the chart in the FIDDLE, you'll see what I mean: the canvas element has a fixed size but the chart itself doesn't fill it fully.

enter image description here

It's almost as if there was a top margin reserved for something that isn't there.

The code:

HTML

<div class="wrapper">
  <canvas id="myChart" width="76" height="76"></canvas>
</div>

JS

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        datasets: [{
            data: [30, 70],
            backgroundColor: [
                'green',
                'gray'
            ],
            borderWidth: 0
        }]
    },
    options: {
        tooltips: {
             enabled: false
        },
        events: []
    }
});

CSS

.wrapper {
  width: 76px;
  height: 76px;
}

Any ideas what I should do to make the pie chart fill the 76x76px canvas?

1 Answer 1

11

The additional space is reserved for the legend, which is enabled by default under options.plugins.legend namespace. Simply disable it and you should have the whole space for the chart:

legend: {
  display: false
}

A working example:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'pie',
  data: {
    datasets: [{
      data: [30, 70],
      backgroundColor: [
        'green',
        'gray'
      ],
      borderWidth: 0
    }]
  },
  options: {
    plugins: {
      tooltips: {
        enabled: false
      },
      legend: {
        display: false  // <- the important part
      },
    },
  }
});
.wrapper {
  width: 76px;
  height: 76px;
  border: 1px solid black; /* for demonstration purposes*/
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div class="wrapper">
  <canvas id="myChart" width="76" height="76"></canvas>
</div>

Sign up to request clarification or add additional context in comments.

8 Comments

Jackpot! It felt kinda weird to be talking about a "margin reserved for something that isn't there" but there we go.
Well, you're right. You can report that behaviour here, if you want: github.com/chartjs/Chart.js/issues ;)
Bravo!! Sir, you just saved my life!
Answer is good but doesn't resolve the problem with the last version, tooltip false and legend false
@Leandro I updated my answer to the latest Chart.js version, my approach is still working.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.