ChartJS ignoring TailwindCSS styling

Viewed 826

I implemented a simple Chart for visualisation und wanted to styling it's height und width using TailwindCSS like this:

  <div class="w-1/2 md:w-full h-full bg-gray-900">
    <canvas class="w-full h-full" id="myChart" />
  </div>

Chart Options:

options: {
          responsive: true,
          aspectRatio: 1
        }

While most of the time the outcome looks good, on some aspect ratios I get weird scalings: enter image description here

Here the graph should be much smaller, since the Div is getting scaled down.:

enter image description here


However, when I add height="100%" to the canvas HTML tag, the scaling works just fine:

  <div class="w-1/2 md:w-full h-full bg-gray-900">
    <canvas height="100%" class="w-full h-full" id="myChart" />
  </div>

enter image description here

Did I misuse the TailwindCSS operators (h-full), which has the same height=100% value, or am I missing something obvious?

2 Answers

Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes. Check this Doc

<div class="relative m-auto w-1/2 h-auto" style="position: relative; height:40vh; width:80vw">
   <canvas class="w-full h-full" id="myChart" /> //give your target width & height
</div>

Found the solution in my object options, where i had to add

maintainAspectratio: false

to get the result i wanted:

options: {
          responsive: true,
          aspectRatio: 1,
          maintainAspectRatio: false
        }
Related