当我为图表 div 设置带有样式属性的高度时,Horizo​​ntalBar 图表显示在 canvas 下方(Chart.js 2.9.4)

HorizontalBar chart is displayed below canvas when I set height with style attribute for chart div (Chart.js 2.9.4)

如果我用图表的样式属性设置高度 div

<div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>

图表看起来像这样(图表显示在 canvas 下方):

var barChartData = {
  labels: [""],
  datasets: [{
      label: "1",
      backgroundColor: "rgba(68,222,166,1)",
      barThickness: 50,
      data: [177]
    },
    {
      label: "2",
      barThickness: 50,
      backgroundColor: "rgba(218, 65, 102, 1)",
      data: [170]
    }
  ]
};

var optionsBar = {
  legend: false,
  title: {
    display: false    
  },
  scales: {
    xAxes: [{
      stacked: true,
      display: false
    }],
    yAxes: [{
      stacked: true,
      display: false
    }]
  }
};


var ctx = document.getElementById("chart");
var myChart = new Chart(ctx, {
  type: 'horizontalBar',
  data: barChartData,
  options: optionsBar
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>

<body style="background-color: grey;">
<div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>
</body>

如何解决?

之所以这样显示,是因为 canvas 的纵横比随 window 尺寸自动变化,但您已将 div 设置为 100px 的特定高度.这就是为什么 canvas 放在 div 之外而 window 大小正在扩展的原因。只是为了摆脱这个问题,以这种方式在您的选项中设置 maintainAspectRatio: false

var barChartData = {
    labels: [""],
    datasets: [{
        label: "1",
        backgroundColor: "rgba(68,222,166,1)",
        barThickness: 50,
        data: [177]
    },
    {
        label: "2",
        barThickness: 50,
        backgroundColor: "rgba(218, 65, 102, 1)",
        data: [170]
    }
    ]
};

var optionsBar = {
    maintainAspectRatio: false,
    legend: false,
    title: {
        display: false
    },
    scales: {
        xAxes: [{
            stacked: true,
            display: false
        }],
        yAxes: [{
            stacked: true,
            display: false
        }]
    }
};


var ctx = document.getElementById("chart");
var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: barChartData,
    options: optionsBar
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>

<body style="background-color: grey;">
    <div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>
</body>