在使用 Chart.js 时,options 对象允许你定制图表的行为和外观。
常用配置
基本设置
responsive: true 是否响应式调整图表大小。
maintainAspectRatio: true 是否保持图表宽高比。
图表标题
plugins.title.display: true
是否显示标题。
plugins.title.text: “Your Chart Title”
图表标题的文本。
plugins.title.font: { size: 20, family: “Arial”, weight: “bold” }
标题字体设置。
图例 (Legend)
plugins.legend.display: true
是否显示图例。
plugins.legend.position: “top” | “left” | “right” | “bottom”
图例位置。
plugins.legend.labels: { font: { size: 12 }, color: “black” }
图例标签样式。
legend:是否显示标题,默认显示
options: {legend: {display: false}}
提示框 (Tooltips)
plugins.tooltip.enabled: true
是否启用提示框。
plugins.tooltip.mode: “nearest” | “index” | “dataset” | “point”
提示框的触发模式。
plugins.tooltip.intersect: true
是否仅在交叉点触发。
plugins.tooltip.callbacks: 自定义提示内容,格式如:
callbacks: {
label: function(tooltipItem) {
return `${tooltipItem.dataset.label}: ${tooltipItem.raw}`;
}
}
坐标轴 (Scales)
scales: 定义坐标轴属性。
scales: {
x: {
type: ‘linear’,
title: { display: true, text: ‘X-Axis Title’ }
},
y: {
beginAtZero: true,
title: { display: true, text: ‘Y-Axis Title’ }
}
}
常见设置:
beginAtZero
:true
– 坐标轴从零开始。min
和max
: 自定义坐标轴最小值和最大值。grid
: 是否显示网格线(grid.display
)。ticks
: 自定义刻度样式,例如font
,color
,stepSize
。
动画 (Animation)
animation: 控制动画效果。
animation: {
duration: 1000, // 动画持续时间 (ms)
easing: “easeInOutQuad”, // 动画缓动效果
}
外观样式
layout.padding: 设置图表的内边距。
layout: {
padding: { top: 10, left: 10, right: 10, bottom: 10 }
}
elements: 自定义图表元素样式。
elements: {
point: { radius: 5, backgroundColor: ‘red’ }, // 数据点样式
line: { tension: 0.4, borderWidth: 2 }, // 折线样式
}
自定义事件
onClick: 点击事件处理。
onClick: (e, elements) => {
console.log(elements); // 当前点击的图表元素信息
}