Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React chart : prevent chart's canvas scaling with height and width

I am using Horizontal Bar from react-chart-js (https://github.com/reactchartjs/react-chartjs-2/blob/react16/example/src/charts/HorizontalBar.js) as below,

  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,
        },
      ],
    },
  };

and

<div>
  <HorizontalBar data={data} options={chartOptions}/>
</div>

I tried applying height on to div or horizontal bar directly to restrict scaling up of the canvas but it dint solve though. Is it possible to supply height and width to the canvas of chart respectively.

like image 268
Dy4 Avatar asked Oct 15 '25 16:10

Dy4


2 Answers

In my case, setting maintainAspectRatio:false along with supplying height/width on div

<div style={{height:'100px',width:'200px'}}>
<HorizontalBar data={data} options={chartOptions}/>
</div>

helped in restricting the canvas's scalability.

Relevant Source: https://www.chartjs.org/docs/latest/general/responsive.html#important-note

like image 71
Dy4 Avatar answered Oct 18 '25 07:10

Dy4


Try setting responsive: false in your options object. That should according to the documentation make so that the canvas doesn't resize (https://www.chartjs.org/docs/latest/general/responsive.html#configuration-options)

like image 35
LeeLenalee Avatar answered Oct 18 '25 06:10

LeeLenalee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!