Chart.js时间轴图表配置故障:按时间统计访问量无法渲染
解决Chart.js时间轴渲染失败及刻度显示错误问题
你的问题核心是时间轴配置层级错误,导致Chart无法解析配置而渲染失败;注释配置后因默认时间格式不匹配,出现刻度显示异常。以下是具体修复方案:
1. 修正时间轴配置结构
Chart.js的displayFormats属于time配置的子属性,而非x轴的直接属性。你之前把它放在x轴根层级,导致配置无效,触发渲染失败。同时注意:Chart.js v3+ 推荐使用小写格式标识(如yyyy表示四位年份),部分适配器兼容大写YYYY但标准写法更稳妥。
修改后的x轴配置片段:
x: { type: "time", time: { unit: "year", displayFormats: { // 移到time对象内部 year: "yyyy" } }, }
2. 完整修复后的代码
import { ChartColors } from "$fresh_charts/utils.ts"; import Chart from "../../islands/chart.tsx"; const data = [ { x: "2016-12-25", y: 20 }, { x: "2017-12-26", y: 10 }, { x: "2020-12-26", y: 10 }, { x: "2024-12-26", y: 10 }, ] export default function ChartPage(props) { return ( <div class="p-4 mx-auto max-w-screen-md"> <Chart type="line" options={{ scales: { x: { type: "time", time: { unit: "year", displayFormats: { year: "yyyy" } }, }, y: { beginAtZero: true }, }, }} data={{ datasets: [ { label: "总访问量", data: data, borderColor: ChartColors.Blue, borderWidth: 1, }, ], }} /> </div> ); }
3. 多维度适配说明
如果需要切换到小时/日/月维度,只需同步修改time.unit和displayFormats的对应键即可:
- 小时维度:
unit: "hour",displayFormats: { hour: "HH:mm" } - 日维度:
unit: "day",displayFormats: { day: "MM-dd" } - 月维度:
unit: "month",displayFormats: { month: "yyyy-MM" }
若出现日期解析异常,可手动将x值转换为Date对象:{ x: new Date("2016-12-25"), y: 20 }
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

