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

如何在Chart.js 3.x.x中修改主刻度(major ticks)的字体样式?

Chart.js 3.x.x 时间轴主刻度字体样式修改问题

我查过旧问题,了解到Chart.js 2.x.x中可通过options.scales.xAxes.ticks.major.fontStyle属性修改主刻度字体样式,但该属性在3.x.x版本中已失效。

我推测3.x.x版本采用font对象配置,于是尝试在options.scales.x.ticks.major中添加font对象:

ticks: {
    major: {
        enabled: true,
        font: {
           weight: 'bold'
        },
    },

但此操作无效果。

随后我尝试在options.scales.x.ticks中使用回调函数,虽能通过添加"--"标识主刻度,但无法修改其字体格式:

callback: function(value, index, ticks) {
    if(ticks[index].major == true) {
        return "--" + value + "--";
    }
    else {
        return value;
    }
}

最后我参考相关问题中的「脚本化选项」方案,尝试在options.scales.x.ticks.font.weight中添加脚本,完整配置如下:

const bgPlugin = {
    id: 'customBgColor',
    beforeDraw: (chart, args, options) => {
        const {ctx} = chart;
        ctx.save();
        ctx.globalCompositeOperation = 'destination-over';
        ctx.fillStyle = options.color || "#f5f3ef";
        ctx.fillRect(0, 0, chart.width, chart.height);
        ctx.restore();
    }
};

var data = {
  datasets: [{/* formatted data is inserted here by the PHP parent script */}]};
  
var config = {
  type: 'line',
  data: data,
  options: {
    parsing: false,
    animation: false,
    plugins: {
      decimation: {
        enabled: true,
        algorithm: 'min-max',
      },
      customBgColor: {
          color: "#f5f3ef",
      }
    },
    scales: {
        x: {
            type: 'time',
            adapters: {
                date: {
                    zone: "America/Los_Angeles",
                },
            },
            ticks: {
                major: {
                    enabled: true,
                },
                font: {
                    weight: (c) => {
                        if(c.major == true) {
                            return 'bold';
                        }
                        else {
                            return 'normal';
                        }
                    }
                },
            }, 
        },
    },
  },
  plugins: [bgPlugin],
};

以下是不同时间范围生成的两张图表示例,主刻度分别为“5 PM”等(第一张)和日期(第二张),但均未显示为粗体:

三个传感器的温度图表

更大时间范围的同类图表

我确信这是正确的实现思路,但代码一定存在问题,恳请帮忙排查。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:49:50