主题
动画与交互
Chart.js 支持丰富的动画效果和交互配置。你可以为图表加载设置动画,也可以定义动画完成的回调函数,实现更复杂的交互行为。同时,图表支持鼠标悬停、点击等事件响应,使用户能够与图表更好地交互。
js
(function () {
const ctx = document.getElementById("animationChart").getContext("2d");
new Chart(ctx, {
type: "line",
data: {
labels: ["一月", "二月", "三月", "四月", "五月"],
datasets: [
{
label: "销量趋势",
data: [10, 20, 15, 30, 25],
borderColor: "rgb(54, 162, 235)",
fill: false,
tension: 0.4,
},
],
},
options: {
responsive: true,
animation: {
duration: 2000,
easing: "easeInOutQuart",
onComplete: function () {
console.log("动画完成!");
},
},
interaction: {
mode: "nearest",
axis: "x",
intersect: false,
},
plugins: {
tooltip: {
enabled: true,
},
},
onClick: (event, elements) => {
if (elements.length) {
const index = elements[0].index;
alert(`点击了:${index + 1} 月`);
}
},
},
});
})();示例无法以 iframe 加载(请检查路径或将 demo 放到 public/)。