Categories
JavaScript Answers

How to fix Charts.js graph not scaling to canvas size with JavaScript?

Spread the love

Sometimes, we want to fix Charts.js graph not scaling to canvas size with JavaScript.

In this article, we’ll look at how to fix Charts.js graph not scaling to canvas size with JavaScript.

How to fix Charts.js graph not scaling to canvas size with JavaScript?

To fix Charts.js graph not scaling to canvas size with JavaScript, we set the responsive option to false.

For instance, we write

const ctx = document.getElementById("myChart").getContext("2d");
const myChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    datasets: [
      {
        label: "My First dataset",
        data: [1, 2, 3, 2, 1, 2, 3, 4, 5, 4],
      },
    ],
  },
  options: {
    responsive: false,
  },
});

to set options.responsive to false to make the graph scale to the canvas size.

We get the canvas with getElementById and get its context with getContext.

Conclusion

To fix Charts.js graph not scaling to canvas size with JavaScript, we set the responsive option to false.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *