ArticleZip > Google Chart Redraw Scale On Window Resize

Google Chart Redraw Scale On Window Resize

Google Chart is a powerful tool for creating interactive and visually appealing charts for your web applications. One common challenge developers face when using Google Charts is ensuring that the chart smoothly adjusts its scale when the window is resized. In this article, we will guide you through the process of dynamically redrawing a Google Chart to maintain a consistent scale when the window size changes.

To get started, you will need to include the Google Charts library in your project. You can do this by adding the following script tag to your HTML file:

Html

Next, you will need to define a function that initializes the Google Charts library and draws the chart. For this example, let's create a simple line chart:

Javascript

google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ["Year", "Sales", "Expenses"],
    ["2014", 1000, 400],
    ["2015", 1170, 460],
    ["2016", 660, 1120],
    ["2017", 1030, 540],
  ]);

  var options = {
    title: "Company Performance",
    curveType: "function",
    legend: { position: "bottom" },
  };

  var chart = new google.visualization.LineChart(
    document.getElementById("chart_div")
  );

  chart.draw(data, options);
}

In the code above, we are loading the corechart package from the Google Charts library and defining a simple line chart with some mock data. The `drawChart` function initializes the chart and draws it inside a div with the id `chart_div`.

Now, let's add an event listener to detect when the window is resized and redraw the chart accordingly:

Javascript

window.addEventListener("resize", function () {
  drawChart();
});

By adding this event listener, every time the window is resized, the `drawChart` function will be called, effectively redrawing the chart to fit the new dimensions of the window.

To prevent multiple chart instances from being created on each resize event, you can remove the existing chart before redrawing it:

Javascript

var chart;

function drawChart() {
  if (chart) {
    chart.clearChart();
  }

  // Chart drawing code here
}

By checking if the chart instance exists and clearing it before redrawing the chart, you ensure that only one instance of the chart is present at any given time.

In conclusion, dynamically redrawing a Google Chart to scale on window resize is a straightforward process that involves initializing the chart library, defining the chart, and adding an event listener to handle window resize events. By following these steps and implementing the suggested modifications, you can create a responsive and user-friendly charting experience for your web application.

×