You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整Hours图表至Amount图表尺寸并修复窗口Resize无动态变化问题

图表尺寸与自适应修复问题

问题详情

  • Hours/Category/Country图表初始尺寸过小,需要调整至与Amount/Category/Country图表(固定600×400)一致
  • 已编写窗口尺寸变化时动态调整图表尺寸的代码,但完全未生效

当前网页显示效果:
网页当前显示效果

现有代码

Hours/Category/Country 代码

<script>

  var chart, options, data;

  google.charts.load('current', {packages: ['corechart', 'bar']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    data = google.visualization.arrayToDataTable([
      ['Genre', 'Fantasy &amp; Sci Fi', 'Romance', 'Mystery/Crime', 'General', 'Western', 'Literature', { role: 'annotation' } ],
      ['2010', 10, 24, 20, 32, 18, 5, ''],
      ['2020', 16, 22, 23, 30, 16, 9, ''],
      ['2030', 28, 19, 29, 30, 12, 13, '']
    ]);

    options = {
      legend: { position: 'top', maxLines: 3 },
      bars: 'vertical',
      isStacked: true,
      vAxis: {format: 'decimal'},
      chartArea: {
        left: 100,
        top: 100,
        right: 80,
        bottom: 80,
        width: '80%',
        height: '70%'
      }
    };

    const chartContainer = document.getElementById('hours-category-country');
    options.width = chartContainer.offsetWidth;
    options.height = chartContainer.offsetHeight;

    chart = new google.visualization.ColumnChart(chartContainer);

    chart.draw(data, options);

    window.dispatchEvent(new Event('resize'))

  }

  // On window resize, redraw the chart with new width and height.
  window.addEventListener('resize', function () {
    const chartContainer = document.getElementById('hours-category-country');
    options.width = chartContainer.offsetWidth;
    options.height = chartContainer.offsetHeight;
    chart.draw(data, options);
  });

</script>

Amount/Category/Country 代码

<script>

  google.charts.load('current', {packages: ['corechart', 'bar']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    const data = google.visualization.arrayToDataTable([
      ['Genre', 'Fantasy &amp; Sci Fi', 'Romance', 'Mystery/Crime', 'General', 'Western', 'Literature', { role: 'annotation' } ],
      ['2010', 10, 24, 20, 32, 18, 5, ''],
      ['2020', 16, 22, 23, 30, 16, 9, ''],
      ['2030', 28, 19, 29, 30, 12, 13, '']
    ]);

    const options = {

      width: 600,
      height: 400,
      legend: { position: 'top', maxLines: 3 },
      bars: 'vertical',
      isStacked: true,
      vAxis: {format: 'decimal'},
      chartArea: {
        left: 100,
        top: 100,
        right: 80,
        bottom: 80,
        width: '80%',
        height: '70%'
      }
      
    };

    const chart = new google.visualization.ColumnChart(document.getElementById('amount-category-country'));

    chart.draw(data, options);
  }
  
</script>

修复方案

1. 解决初始尺寸过小问题

直接在Hours图表的options中设置与Amount图表一致的固定宽高,替换原来基于容器获取尺寸的代码:

options = {
  // 保留原有配置
  legend: { position: 'top', maxLines: 3 },
  bars: 'vertical',
  isStacked: true,
  vAxis: {format: 'decimal'},
  chartArea: {
    left: 100,
    top: 100,
    right: 80,
    bottom: 80,
    width: '80%',
    height: '70%'
  },
  // 添加固定宽高,对齐Amount图表
  width: 600,
  height: 400
};

如果需要图表跟随容器尺寸变化,先给容器hours-category-country添加CSS样式确保其有尺寸:

#hours-category-country {
  width: 600px;
  height: 400px;
  min-width: 600px;
}

2. 修复窗口resize不生效问题

原代码的问题在于:初始化时手动触发resize事件可能导致混乱,且resize时无防抖处理容易引发异常。修改后的完整代码如下:

<script>
var chart, options, data;

google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  data = google.visualization.arrayToDataTable([
    ['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General', 'Western', 'Literature', { role: 'annotation' } ],
    ['2010', 10, 24, 20, 32, 18, 5, ''],
    ['2020', 16, 22, 23, 30, 16, 9, ''],
    ['2030', 28, 19, 29, 30, 12, 13, '']
  ]);

  options = {
    legend: { position: 'top', maxLines: 3 },
    bars: 'vertical',
    isStacked: true,
    vAxis: {format: 'decimal'},
    chartArea: {
      left: 100,
      top: 100,
      right: 80,
      bottom: 80,
      width: '80%',
      height: '70%'
    },
    width: 600,
    height: 400
  };

  const chartContainer = document.getElementById('hours-category-country');
  // 若需自适应容器,取消注释并确保容器有CSS尺寸
  // options.width = chartContainer.offsetWidth || 600;
  // options.height = chartContainer.offsetHeight || 400;

  chart = new google.visualization.ColumnChart(chartContainer);
  chart.draw(data, options);
}

// 防抖函数,避免resize时频繁重绘
function debounce(func, delay) {
  let timeoutId;
  return function() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(func, delay);
  };
}

window.addEventListener('resize', debounce(function () {
  const chartContainer = document.getElementById('hours-category-country');
  if (!chartContainer || !chart) return;

  // 自适应容器尺寸时打开下面两行注释
  // options.width = chartContainer.offsetWidth || 600;
  // options.height = chartContainer.offsetHeight || 400;

  chart.draw(data, options);
}, 200));
</script>

关键修改点

  • 移除初始化时手动触发的resize事件,避免逻辑混乱
  • 添加防抖函数,减少窗口调整时的图表重绘次数,提升性能
  • 在resize回调中增加存在性检查,避免空指针报错
  • 直接对齐Amount图表的固定尺寸,解决初始过小问题

内容的提问来源于stack exchange,提问作者Borgher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:51:00