Make Google Chart Gauge responsive

前端 未结 2 1846
小鲜肉
小鲜肉 2020-12-09 14:39

I would like to create a Google Gauge charts which should be web-responsive. I heard about setting the width to \'100%\' should work out, but it actually doesn\'t make any c

相关标签:
2条回答
  • 2020-12-09 15:12

    You can just just assign the width 100% in options and a responsive div tag with width="100%" or here goes fiddle link where you can see the live demo.

    //html here

     <div class="row"> 
       <div class="col-xs-12 col-sm-6">
        <div id="chart_div"></div>
      </div>
     </div>
    

    //js here

     var options = {'title':'How Much Pizza I Ate Last Night',
                       'width':'100%',
                      };
    
    0 讨论(0)
  • 2020-12-09 15:15

    The charts will not resize automatically. You must set up an event handler that calls chart.draw(data, options); on resize:

    function drawChart () {
        var data = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['Happiness', 40]
        ]);
    
        var options = {
            redFrom: 0,
            redTo: 40,
            yellowFrom:40,
            yellowTo: 70,
            greenFrom: 70,
            greenTo: 100,
            minorTicks: 5
        };
    
        var chart = new google.visualization.Gauge(document.getElementById('test'));
        chart.draw(data, options);
    
        function resizeHandler () {
            chart.draw(data, options);
        }
        if (window.addEventListener) {
            window.addEventListener('resize', resizeHandler, false);
        }
        else if (window.attachEvent) {
            window.attachEvent('onresize', resizeHandler);
        }
    }
    

    Setting height and width to 100% in the options won't do anything for you. You will need to set those in CSS for your container div:

    #test {
        height: 100%;
        width: 100%;
    }
    

    Keep in mind a few things: setting height to 100% doesn't do anything unless the parent element has a specific height; also, the height and width of a Gauge are determined by the smaller of the dimensions. So if you increase the size of the screen without specifying the height of the container #test (or it's parent container), the likely outcome is that the chart won't change size.

    0 讨论(0)
提交回复
热议问题