使用生态插件
Chart.js 拥有丰富的生态插件,能够扩展图表的功能,比如数据标签(Data Labels)、缩放和平移(Zoom and Pan)等。通过安装并引入这些插件,可以轻松实现更多交互和展示效果。
以下示例演示如何引入并使用 chartjs-plugin-datalabels 插件,为柱状图添加数据标签。
const ctx = document.getElementById("pluginChart").getContext("2d");
Chart.register(window["ChartDataLabels"]);
const pluginChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["红", "蓝", "黄", "绿", "紫", "橙"],
datasets: [
{
label: "销量",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: "rgba(255, 99, 132, 0.7)",
},
],
},
options: {
responsive: true,
plugins: {
datalabels: {
color: "#fff",
anchor: "end",
align: "top",
font: {
weight: "bold",
},
},
legend: { display: true },
},
},
});
源码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Chart.js 生态插件示例</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<style>
body {
max-width: 700px;
margin: 2rem auto;
font-family: sans-serif;
background: #f9f9f9;
padding: 1rem;
text-align: center;
}
canvas {
background: #fff;
border: 1px solid #ccc;
margin: 1rem auto;
}
</style>
</head>
<body>
<canvas id="pluginChart" width="700" height="400"></canvas>
<script>
(function () {
const ctx = document.getElementById(‘pluginChart’).getContext(‘2d’);
Chart.register(window['ChartDataLabels']);
const pluginChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['红', '蓝', '黄', '绿', '紫', '橙'],
datasets: [{
label: '销量',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'rgba(255, 99, 132, 0.7)'
}]
},
options: {
responsive: true,
plugins: {
datalabels: {
color: '#fff',
anchor: 'end',
align: 'top',
font: {
weight: 'bold'
}
},
legend: { display: true }
}
}
});
})();
</script>
</body>
</html>
相关内容
- 什么是 Chart.js? Chart.js 是一个简单易用且功能强大的 JavaScript 图表库,支持多种常见图表类型,帮助开发者快速创建美观且响应式的数据可视化效果,适合初学者和专...
- 安装与引入 介绍如何在项目中安装和引入 Chart.js,包括通过 CDN 快速使用和通过 npm 安装到前端构建环境的多种方式,帮助快速搭建图表开发环境。
- 基本结构与初始化 讲解如何创建图表的基本结构与初始化流程,包括配置画布、准备数据和实例化图表的步骤,帮助快速搭建图表展示。
- 示例:折线图 通过示例讲解如何创建折线图,涵盖数据配置、样式设置和基本交互,帮助快速掌握折线图的绘制技巧。
- 折线图 Line 介绍如何使用 Chart.js 创建折线图,详细讲解数据配置、样式调整及交互功能,帮助快速制作趋势图表。
- 柱状图 Bar 介绍如何使用 Chart.js 创建柱状图,详细讲解数据配置、颜色设置及图表样式,帮助快速绘制直观的条形数据展示。