Set background as transparent and responsive for google Line Chart

979 views Asked by At

I want to use Google linechart .

This is my project's image its a chart for Clappr

My questions:

1) How can I set the background-color:transparent ??

2) If user click on full page size ( button right ) , the chart will not be 100% width again , how to set it 100% ?

This picture is for second question

responsive

3

There are 3 answers

0
Arman On BEST ANSWER

There is only way to reaction about device width (or windows width) and that is redraw chart. It is true, but do not forget to destroy old chart before redraw new version.

 .destroy()

This code can remove old chart , after that you can add new chart

  // Example from the docs
        var myLineChart = new Chart(ctx, config);
   // Destroys a specific chart instance
        myLineChart.destroy();

I tested, It is working fine

3
WhiteHat On

to make the chart's background transparent,
use the following configuration option...

backgroundColor: 'transparent',
chartArea: {
  backgroundColor: 'transparent',
}

to make the chart responsive,
re-draw the chart when the container's size changes,
such as on the window's resize event...

window.addEventListener('resize', function () {
  chart.draw(data, options);
});

see following working snippet,
run the snippet, then click "Full page" to see it change...

note: the container <div> has a cyan background

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y'],
    [0, 0],
    [1, 1],
    [2, 2],
    [3, 3],
    [4, 4],
    [5, 5]
  ]);

  var options = {
    backgroundColor: 'transparent',
    chartArea: {
      backgroundColor: 'transparent',
    }
  };

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

  chart.draw(data, options);
  window.addEventListener('resize', function () {
    chart.draw(data, options);
  });
});
#chart_div {
  background-color: cyan;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

6
Torjescu Sergiu On

You can target via CSS the rect attribute of the chart as follows:

rect { 
   fill: rgb(0,0,0,0);
}

https://jsfiddle.net/kL2vaed4/2/ here is an example where I used a black background so you can see that it works.