ChartJS 忽略 TailwindCSS 样式

时间:2021-06-25 09:48:08

标签: javascript chart.js tailwind-css

我实现了一个简单的可视化图表,并希望使用 TailwindCSS 来设置其高度和宽度的样式,如下所示:

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

图表选项:

options: {
          responsive: true,
          aspectRatio: 1
        }

虽然大多数时候结果看起来不错,但在某些纵横比上,我得到了奇怪的缩放比例: enter image description here

这里的图表应该小得多,因为 Div 正在缩小。:

enter image description here


但是,当我添加 height="100%" 到画布 HTML 标签,缩放效果很好:

  <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

我是否误用了具有相同 height=100% 值的 TailwindCSS 运算符 (h-full),或者我是否遗漏了一些明显的东西?

2 个答案:

答案 0 :(得分:0)

无法直接从画布元素检测画布大小何时发生变化。 Chart.js 使用其父容器来更新画布渲染和显示大小。检查这个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>

答案 1 :(得分:0)

在我必须添加的对象选项中找到解决方案

<块引用>

maintainAspectratio: false

得到我想要的结果:

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