教程 chartjs tutorial

安装与引入

在开始使用 Chart.js 之前,首先需要将库引入到你的项目中。根据不同的开发环境,主要有两种常用的方式:

通过 CDN 引入

这是最快速的方式,只需在 HTML 页面中添加以下 <script> 标签,即可使用最新稳定版的 Chart.js,无需额外安装:

html
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

通过 CDN 引入适合快速演示和小型项目,但在生产环境中推荐使用模块化方式管理依赖。

通过 npm 安装

对于使用现代前端构建工具(如 Vite、Webpack、Rollup 等)的项目,可以通过 npm 或 yarn 安装:

bash
npm install chart.js
# 或者
yarn add chart.js

安装完成后,在你的 JavaScript 文件中导入 Chart.js:

js
import { Chart, registerables } from "chart.js";
Chart.register(...registerables);

这种方式能更好地支持按需引入,减少包体积。

代码演示

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>Chart.js 安装与引入示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 600px; margin: 2rem auto; font-family: Arial, sans-serif; } </style> </head>

<body> <h2>通过 CDN 引入使用 Chart.js</h2> <canvas id="cdnChart" width="600" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘cdnChart’).getContext(‘2d’); new Chart(ctx, { type: ‘bar’, data: { labels: [‘红’, ‘蓝’, ‘黄’, ‘绿’, ‘紫’, ‘橙’], datasets: [{ label: ‘样本数据’, data: [12, 19, 3, 5, 2, 3], backgroundColor: [ ‘rgba(255, 99, 132, 0.7)’, ‘rgba(54, 162, 235, 0.7)’, ‘rgba(255, 206, 86, 0.7)’, ‘rgba(75, 192, 192, 0.7)’, ‘rgba(153, 102, 255, 0.7)’, ‘rgba(255, 159, 64, 0.7)’ ] }] }, options: { responsive: true, plugins: { legend: { display: true } } } }); })();

</script> </body>

</html>