教程 chartjs tutorial

基本结构与初始化

使用 Chart.js 创建图表,首先需要准备一个 HTML 画布元素 <canvas>,作为图表的渲染区域。然后通过 JavaScript 代码初始化 Chart 实例,传入配置项完成图表绘制。

1. 准备 Canvas 元素

在 HTML 中添加一个 <canvas> 标签,指定宽度和高度,作为图表的容器:

html
<canvas id="myChart" width="600" height="400"></canvas>

2. 初始化 Chart 实例

在 JavaScript 中,通过获取 Canvas 上下文,创建 Chart 对象,指定图表类型和数据配置:

js
const ctx = document.getElementById("myChart").getContext("2d");
const myChart = new Chart(ctx, {
  type: "bar", // 图表类型,如 line, bar, pie 等
  data: {
    labels: ["一月", "二月", "三月", "四月", "五月"],
    datasets: [
      {
        label: "示例数据",
        data: [10, 20, 30, 40, 50],
        backgroundColor: "rgba(75, 192, 192, 0.6)",
      },
    ],
  },
  options: {
    responsive: true,
  },
});

3. 配置说明

  • type:指定图表类型,如折线图(line)、柱状图(bar)、饼图(pie)等。
  • data:包含标签(labels)和数据集(datasets)。
  • options:配置图表行为和样式,如响应式、动画等。

通过以上步骤,即可快速完成基本图表的创建。

代码演示

在线代码演示
源码
<!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; }

canvas {
  background: #fafafa;
  border: 1px solid #ccc;
}

</style> </head>

<body> <h2>基本柱状图示例</h2> <canvas id="myChart" width="600" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘myChart’).getContext(‘2d’); const myChart = new Chart(ctx, { type: ‘bar’, data: { labels: [‘一月’, ‘二月’, ‘三月’, ‘四月’, ‘五月’], datasets: [{ label: ‘示例数据’, data: [10, 20, 30, 40, 50], backgroundColor: ‘rgba(75, 192, 192, 0.6)’ }] }, options: { responsive: true } }); })(); </script>

</body>

</html>