如何在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
相关产品推荐
相关产品推荐

