响应式Google图表的最佳做法

我在我的网站上有这个谷歌图表 。 现在这是一个Scatter图表,但我想要所有类型的图表的解决方案。 例如,如果您使用700像素宽的窗口加载网站,则图表尺寸不响应:图表太宽。 以下是我正在使用的代码。

你能帮助我吗 ?

谢谢

HTML:

CSS:

 #chart_div { width:100%; height:20%; } 

JS:

 var options = { title: 'Weight of pro surfer vs. Volume of his pro model', hAxis: {title: 'Weight (kg)', minValue: 53, maxValue: 100}, //55 vAxis: {title: 'Volume (l)'}, //, minValue: 20, maxValue: 40}, //20 legend: 'none', width: '100%', height: '100%', colors: ['#000000'], series: { 1: { color: '#06b4c8' }, }, legend: {position: 'top right', textStyle: {fontSize: 8}}, chartArea: {width: '60%'}, trendlines: { 0: {//type: 'exponential', visibleInLegend: true, color: 'grey', lineWidth: 2, opacity: 0.2, labelInLegend: 'Linear trendline\n(Performance)' } } // Draw a trendline for data series 0. }; var chart = new google.visualization.ScatterChart(document.getElementById('chart_div')); chart.draw(data, options); google.visualization.events.addListener(chart, 'ready', myReadyHandler()); function myReadyHandler() { chartDrawn.resolve(); } 

编辑:似乎div #chart_div具有正确的大小(我用css设置的那个),但是这个div中的图表不适应它的大小…它保持锁定查看图像: 在此处输入图像描述

由于Visualization API图表根本没有响应,因此您必须自己处理所有内容。 通常,这意味着要监听窗口“resize”事件并重新绘制图表(根据需要设置任何尺寸):

 function resize () { // change dimensions if necessary chart.draw(data, options); } if (window.addEventListener) { window.addEventListener('resize', resize); } else { window.attachEvent('onresize', resize); } 

对我来说,以上都没有,或者它们太复杂了我试试。

我发现的解决方案很简单,效果很好。 它只涉及构建一个普通的Google图表,在我的例子中是一个圆环图,然后使用CSS进行样式化。

 @media screen and (max-width: 1080px) { div#donutchart { zoom:0.6; margin-left:-16%; } } 

就这样。 当然,您可以为最大宽度,缩放和边距设置其他值,以使图表完美匹配。 我的图表是800×600( 你可以在这里看到 )。

将宽度设置为图表的100%并调用resize函数,如下所示

 $(window).resize(function(){ yourCallingChartFunction(); }); 

对于响应负载工作:

 #chart_div { width:inherit; height:inherit; } 

当会话期间屏幕尺寸发生变化时,它不会起作用。

如果您使用的是Twitter Bootstrap,那么从v3.2开始,您可以利用embed-responsive样式:

 

或者如果你想要4:3的宽高比:

 

一个更有效的resize片段在下面并且可以重复使用;

 //bind a resizing function to the window $(window).resize(function() { if(this.resizeTO) clearTimeout(this.resizeTO); this.resizeTO = setTimeout(function() { $(this).trigger('resizeEnd'); }, 500); }); //usage of resizeEnd $(window).bind('resizeEnd', function() { DoSomething(); }); 

我发现这个代码笔示例很有用: Google Charts的代码笔示例响应他们使用jQuery在窗口resize上重绘图形:

 $(window).resize(function(){ yourCartdrawChartfuntion(); });