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

如何限制Chart.js仅显示已有轴值,禁止拖拽超出数据日期范围

限制Chart.js拖拽(Pan)仅在数据日期范围内

要解决拖拽时出现无数据日期的问题,只需通过两步限制x轴的拖拽边界:

  • 提取数据中的最小、最大日期作为范围边界
  • 在zoom插件的拖拽配置中添加范围限制

修改后的完整代码

import "./styles.css";
import { Bar } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  Title,
  LinearScale,
  PointElement,
  Tooltip,
  Legend,
  TimeScale,
  BarElement
} from "chart.js";
import "chartjs-adapter-date-fns";
import zoomPlugin from "chartjs-plugin-zoom";
import { useRef } from "react";
import { parseISO } from "date-fns";

ChartJS.register(
  BarElement,
  CategoryScale,
  LinearScale,
  Title,
  Tooltip,
  Legend,
  zoomPlugin,
  TimeScale
);

export default function App() {
  // 原始数据
  const rawData = [
    { x: "2021-01-01", y: 10 },
    { x: "2021-01-02", y: 20 },
    { x: "2021-01-03", y: 20 },
    { x: "2021-01-04", y: 20 },
    { x: "2021-01-05", y: 20 }
  ];

  // 提取数据中的最小/最大日期
  const dates = rawData.map(item => parseISO(item.x));
  const minDate = new Date(Math.min(...dates));
  const maxDate = new Date(Math.max(...dates));

  const options = {
    maintainAspectRatio: false,
    responsive: true,
    elements: {
      point: {
        radius: 0
      },
      line: {
        borderWidth: 1.5
      }
    },
    scales: {
      x: {
        type: "time",
        time: {
          unit: "day"
        },
        // 设置x轴初始显示范围为数据的完整日期区间
        min: minDate,
        max: maxDate,
        ticks: {
          color: "rgba( 0, 0, 1)"
        },
        grid: {
          color: "rgba(0, 0, 0, 1)"
        }
      },
      y: {
        ticks: {
          color: "rgba(0, 0, 0, 1)"
        },
        grid: {
          color: "rgba(0, 0, 0, 1)"
        }
      }
    },
    plugins: {
      zoom: {
        pan: {
          enabled: true,
          mode: "x",
          speed: 10,
          // 限制拖拽范围在数据的日期区间内
          limits: {
            x: {
              min: minDate.getTime(),
              max: maxDate.getTime()
            }
          }
        }
      }
    }
  };

  const data = {
    datasets: [
      {
        data: rawData
      }
    ]
  };

  const canvasRef = useRef();
  return (
    <div className="App">
      <Bar
        ref={canvasRef}
        options={options}
        data={data}
        height={null}
        width={null}
      />
    </div>
  );
}

关键修改说明

  1. 提取日期边界:用parseISO将字符串日期转为Date对象,再通过Math.min/Math.max获取数据的最小、最大日期
  2. 初始范围锁定:在scales.x中设置min和max,确保图表默认显示完整数据区间
  3. 拖拽范围限制:在plugins.zoom.pan.limits.x中传入日期时间戳,Chart.js会自动拦截超出边界的拖拽操作,避免显示无数据的日期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:24:35