Google chart redraw/scale on window resize

前端 未结 9 1298
甜味超标
甜味超标 2020-12-07 19:50

How do I redraw/rescale a google linechart on window resize?

相关标签:
9条回答
  • 2020-12-07 20:34

    This is the simplest way I can work out of doing this without causing too much stress to the browser:

        var chart1 = "done";
    
    $(window).resize(function() {
    if(chart1=="done"){
    chart1 = "waiting";
    setTimeout(function(){drawChart();chart1 = "done"},1000);
    }
    });
    

    All it does is wait 1 second before the chart reloads and doesn't let the function call again in this waiting period. as window resize functions are called multiple times any time you change the window size this helps make the function only actually work once each time you change the window size, the rest of the calls get stopped by the if statement.

    I hope this helps

    0 讨论(0)
  • There is no option in Google Visualization API to make Google Charts responsive.

    But we can make Google Charts responsive as Window Resizes. To make Google Chart responsive there is jQuery library available at GitHub - jquery-smartresize licensed under MIT License, which has the ability to resize graphs on window resize event.

    This project on GitHub has two script files :-

    jquery.debouncedresize.js: adds a special event that fires once after the window
    has been resized.
    

    &

    jquery.throttledresize.js: adds a special event that fires at a reduced rate (no 
    more double events from Chrome and Safari).
    

    Here are two examples of responsive charts...

    1. Responsive Google Pie Chart
    2. Responsive Google Bar Chart

    We can change the bottom padding of visualization_wrap to match the desired aspect ratio of chart.

    Calculate as Height / Width x 100
    For a 16x9 display it would be 9/16 = 0.5625 x 100 = 56.25%
    For a square it'd be 100%
    

    We can customize chartarea option of Google Chart to ensure that labels don't get cut off on resizing.

    0 讨论(0)
  • 2020-12-07 20:37

    I personally prefer the following approach, if You can live with using addEventListener, and don't mind lack of support for IE < 9.

    var windowResizeTimer;
    window.addEventListener('resize', function(e){
        clearTimeout(windowResizeTimer);
        windowResizeTimer = setTimeout(function(){
            chart.draw(data, options);
        }, 750);
    });
    

    Note the use of the setTimeout() and clearTimeout() functions and the added delay of 750 milliseconds, which makes this slightly less intensive when multiple resize events fire in quick succession (which is often the case for browsers on desktop when resizing using a mouse).

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