React图表:防止图表的画布随高度和宽度缩放

Dy4*_*Dy4 4 javascript reactjs chart.js react-chartjs react-chartjs-2

我正在使用react-chart-js(https://github.com/reactchartjs/react-chartjs-2/blob/react16/example/src/charts/Horizo ​​ntalBar.js)中的水平条,如下所示,

  const data = {
    label: ["graph"],
    datasets: [
      {
        label: "A",
        backgroundColor: "red",
        data: [50],
      },
      {
        label: "B",
        backgroundColor: "yellow",
        data: [10],
      },
    ],
  };

  const chartOptions = {
    scales: {
      xAxes: [
        {
          stacked: true,
          barPercentage: 0.2,
        },
      ],
      yAxes: [
        {
          stacked: true,
          barPercentage: 0.2,
        },
      ],
    },
  };
Run Code Online (Sandbox Code Playgroud)

<div>
  <HorizontalBar data={data} options={chartOptions}/>
</div>
Run Code Online (Sandbox Code Playgroud)

我尝试直接将高度应用于 div 或水平栏以限制画布的放大,但它并不能解决问题。是否可以分别向图表画布提供高度和宽度。

Dy4*_*Dy4 12

就我而言, maintainAspectRatio:false在 div 上设置高度/宽度

<div style={{height:'100px',width:'200px'}}>
<HorizontalBar data={data} options={chartOptions}/>
</div>
Run Code Online (Sandbox Code Playgroud)

有助于限制画布的可扩展性。

相关来源:https ://www.chartjs.org/docs/latest/general/responsive.html#important-note