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

Chart.js折线图setInterval刷新异常求助:刷新后图表放大显示

Fixing Chart.js Line Chart Refresh (No Zoomed Re-Renders)

Hey there, I’ve run into this exact issue before—let’s get your 10-second refresh working smoothly without that annoying zoomed-in re-render. The problem is that when you recreate the chart every time in setInterval, you’re leaving old chart instances hanging around in the DOM, which causes the visual overlap/zoom effect. Here are two solid solutions:

Option 1: Destroy Old Chart Before Re-Creating (Simple & Reliable)

This method ensures we clean up the old chart instance before making a new one, so there’s no overlap.

// Keep a global reference to your chart instance
let myLineChart = null;

function refreshChart() {
  // Fetch your latest data via AJAX
  fetch('/your-data-api-endpoint')
    .then(res => res.json())
    .then(data => {
      const chartCtx = document.getElementById('your-chart-id').getContext('2d');
      
      // If a chart exists, destroy it first to avoid duplicates
      if (myLineChart) {
        myLineChart.destroy();
      }
      
      // Create the new chart with fresh data
      myLineChart = new Chart(chartCtx, {
        type: 'line',
        data: {
          labels: data.labels, // Your new x-axis labels
          datasets: [{
            label: 'Your Dataset Label',
            data: data.values, // Fresh y-axis values
            borderColor: '#2196F3',
            fill: false,
            tension: 0.2
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: true, // Critical to keep consistent sizing
          // Add any other options you had before
        }
      });
    })
    .catch(err => console.error('Failed to fetch data:', err));
}

// Initialize the chart on page load
refreshChart();
// Set up 10-second refresh interval
setInterval(refreshChart, 10000);

Option 2: Update Existing Chart Data (More Efficient)

Instead of destroying and recreating the chart, we just update its data and trigger a refresh. This is better for performance, especially with large datasets.

// Initialize the chart once with empty data
const chartCtx = document.getElementById('your-chart-id').getContext('2d');
const myLineChart = new Chart(chartCtx, {
  type: 'line',
  data: {
    labels: [],
    datasets: [{
      label: 'Your Dataset Label',
      data: [],
      borderColor: '#2196F3',
      fill: false,
      tension: 0.2
    }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: true,
    // Your other options here
  }
});

function updateChartData() {
  fetch('/your-data-api-endpoint')
    .then(res => res.json())
    .then(data => {
      // Update the chart's data directly
      myLineChart.data.labels = data.labels;
      myLineChart.data.datasets[0].data = data.values;
      
      // Trigger the chart to re-render with new data
      myLineChart.update();
    })
    .catch(err => console.error('Failed to fetch data:', err));
}

// Load initial data
updateChartData();
// Refresh every 10 seconds
setInterval(updateChartData, 10000);

Why Your Original Approach Caused Zooming

When you create a new Chart instance every time without destroying the old one, both instances are rendered in the same canvas element. The old instance doesn’t get removed, so the new one draws on top, creating the illusion of a zoomed-in chart. By either destroying the old instance or updating the existing one, you avoid this overlap.

Quick Tips

  • Make sure maintainAspectRatio is set to true (default) to keep your chart’s size consistent across refreshes.
  • Add error handling to your AJAX call so a failed request doesn’t break the entire refresh cycle.

内容的提问来源于stack exchange,提问作者José Oliveira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:20:19