图例与提示框
Chart.js 提供灵活的图例和提示框配置,方便你展示图表信息。图例可以控制显示与隐藏、调整位置和样式,提示框则支持丰富的内容格式和交互效果,帮助用户更好理解图表数据。
(function () {
const ctx = document.getElementById("legendTooltipChart").getContext("2d");
const legendTooltipChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["苹果", "香蕉", "橙子", "葡萄", "草莓"],
datasets: [
{
label: "水果销量",
data: [12, 19, 7, 15, 10],
backgroundColor: [
"rgba(255, 99, 132, 0.7)",
"rgba(255, 206, 86, 0.7)",
"rgba(54, 162, 235, 0.7)",
"rgba(153, 102, 255, 0.7)",
"rgba(75, 192, 192, 0.7)",
],
},
],
},
options: {
responsive: true,
plugins: {
legend: {
display: true,
position: "top",
labels: {
color: "#444",
font: { size: 14 },
},
onClick: (e, legendItem, legend) => {
const index = legendItem.datasetIndex;
const ci = legend.chart;
ci.toggleDataVisibility(index);
ci.update();
},
},
tooltip: {
enabled: true,
backgroundColor: "rgba(0,0,0,0.8)",
titleFont: { size: 16, weight: "bold" },
bodyFont: { size: 14 },
callbacks: {
label: function (context) {
return `销量: ${context.parsed.y}`;
},
},
},
},
},
});
})();
源码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Chart.js 图例与提示框示例</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
max-width: 700px;
margin: 2rem auto;
font-family: Arial, sans-serif;
background: #fafafa;
padding: 1rem;
}
canvas {
background: #fff;
border: 1px solid #ccc;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="legendTooltipChart" width="700" height="400"></canvas>
<script>
(function () {
const ctx = document.getElementById(‘legendTooltipChart’).getContext(‘2d’);
new Chart(ctx, {
type: ‘bar’,
data: {
labels: [‘苹果’, ‘香蕉’, ‘橙子’, ‘葡萄’, ‘草莓’],
datasets: [{
label: ‘水果销量’,
data: [12, 19, 7, 15, 10],
backgroundColor: [
‘rgba(255, 99, 132, 0.7)’,
‘rgba(255, 206, 86, 0.7)’,
‘rgba(54, 162, 235, 0.7)’,
‘rgba(153, 102, 255, 0.7)’,
‘rgba(75, 192, 192, 0.7)’
]
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: true,
position: ‘top’,
labels: {
color: ‘#444’,
font: { size: 14 }
},
onClick: (e, legendItem, legend) => {
const index = legendItem.datasetIndex;
const ci = legend.chart;
ci.toggleDataVisibility(index);
ci.update();
}
},
tooltip: {
enabled: true,
backgroundColor: ‘rgba(0,0,0,0.8)’,
titleFont: { size: 16, weight: ‘bold’ },
bodyFont: { size: 14 },
callbacks: {
label: function (context) {
return 销量: ${context.parsed.y};
}
}
}
}
}
});
})();
</script>
</body>
</html>
相关内容
- 什么是 Chart.js? Chart.js 是一个简单易用且功能强大的 JavaScript 图表库,支持多种常见图表类型,帮助开发者快速创建美观且响应式的数据可视化效果,适合初学者和专...
- 安装与引入 介绍如何在项目中安装和引入 Chart.js,包括通过 CDN 快速使用和通过 npm 安装到前端构建环境的多种方式,帮助快速搭建图表开发环境。
- 基本结构与初始化 讲解如何创建图表的基本结构与初始化流程,包括配置画布、准备数据和实例化图表的步骤,帮助快速搭建图表展示。
- 示例:折线图 通过示例讲解如何创建折线图,涵盖数据配置、样式设置和基本交互,帮助快速掌握折线图的绘制技巧。
- 折线图 Line 介绍如何使用 Chart.js 创建折线图,详细讲解数据配置、样式调整及交互功能,帮助快速制作趋势图表。
- 柱状图 Bar 介绍如何使用 Chart.js 创建柱状图,详细讲解数据配置、颜色设置及图表样式,帮助快速绘制直观的条形数据展示。