在窗口中重新调整Google图表的大小

时间:2014-02-10 02:27:50

标签: javascript javascript-events charts google-visualization google-chartwrapper

请帮助我在Windows重新调整大小时自动重新调整Google图表的大小。

谢谢

这里有一些代码..

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"]});
        google.setOnLoadCallback(drawChart);
        function drawChart() {
            var data = google.visualization.arrayToDataTable([
                ['Day', 'Open ticket', 'Closed ticket'],
                ['Day 1',  10,   400],
                ['Day 2',  170,  460],
                ['Day 3',  60,   1120],
                ['Day 4',  30,   540],
            ]);
            var options = {
                title: 'DAILY GRAPH',
                hAxis: {title: 'NOVEMBER',  titleTextStyle: {color: '#333'}},
                vAxis: {minValue: 0}
            };
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>

2 个答案:

答案 0 :(得分:4)

这是一种方式:

添加此事件处理程序:

 window.onresize = drawChart;

然后将图表的宽度和高度基于窗口宽度和高度的百分比:

    var width = .4 * window.innerHeight;
    var height = .4 * window.innerWidth;

    var options = {
        title: 'DAILY GRAPH',
        width: width,
        height: height,
        hAxis: { title: 'NOVEMBER', titleTextStyle: { color: '#333' } },
        vAxis: { minValue: 0 }
    };

答案 1 :(得分:3)

您可以在width部分中以百分比定义heighthead,例如:

<style>
    #chart_div {
        width:  80%;
        height: 100%;
    }   
</style>

并将窗口大小调整的事件侦听器添加到drawChart()方法的末尾:

    ...
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);

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

请参阅example at jsbin