3

I've got a just-created empty chart.js chart and it stucks in an animated endless loop. Why? What am I doing wrong?

var initData=
{
  type: "polarArea",
  data: {datasets:[]},
  options: {
    plugins: {},
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      r: {}
    }
  }
};

var context = document.getElementById('test').getContext('2d');
var chart = new Chart(context, initData);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div><canvas style="margin: 0.5em; width: 100%; height: 20em" id="test"></canvas></div>

1
  • Just a guess, that is a demo mode if you do not give any data to the chart? Commented Dec 16, 2021 at 9:52

1 Answer 1

2

This seems to happen because chart.js does not like the small amount of margin, if you increase it it works fine or if you put a surrounding div around it and put the margin on that it also seems to work fine:

var initData = {
  type: "polarArea",
  data: {
    labels: ['a', 'b'],
    datasets: [{
      data: [2, 4]
    }]
  },
  options: {
    plugins: {},
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      r: {}
    }
  }
};

var context = document.getElementById('test').getContext('2d');
var chart = new Chart(context, initData);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

<div>
  <div style="margin: 0.5em;">
    <canvas style="width: 100%; height: 20em;" id="test"></canvas>
  </div>
</div>

Edit:
I was not totally correct with the larger size of margin fixes it, it so happend to just be a correct number.

Chart.js does need a dedicated container around the chart for the margin to function properly as described in the docs here

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

2 Comments

Huhh, thanks, it solved. But shouldn't it be treated as a chartjs bug anyway? Is it wort opening an issue...?
No I was wrong, just got a number of margin it didnt happen for, in the docs its also specified that this behaviour will occur and you will need to use a separate wrapper div on which you apply the styling

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.