chartjs

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Chart.js Quick Charting Skill

Chart.js 快速图表制作技能

Create beautiful, responsive charts in minutes with Chart.js - the simple yet flexible JavaScript charting library.
借助Chart.js——这款简洁却灵活的JavaScript图表库,在几分钟内创建美观、响应式的图表。

When to Use This Skill

何时使用该技能

Use Chart.js when you need:
  • Quick implementation - Up and running in minutes
  • Simple charts - Line, bar, pie, doughnut, radar charts
  • Minimal configuration - Sensible defaults that work out of the box
  • Small projects - Lightweight library (60KB gzipped)
  • Responsive charts - Mobile-friendly by default
  • No dependencies - Standalone library
Avoid when:
  • Complex customization needed (use D3.js)
  • 3D charts required (use Plotly)
  • Advanced scientific visualizations needed (use Plotly)
  • Large datasets >10k points (use Plotly with WebGL)
在以下场景使用Chart.js:
  • 快速实现——几分钟内即可启动并运行
  • 简单图表——折线图、柱状图、饼图、环形图、雷达图
  • 极少配置——开箱即用的合理默认设置
  • 小型项目——轻量级库(压缩后仅60KB)
  • 响应式图表——默认适配移动端
  • 无依赖——独立库
避免使用的场景:
  • 需要复杂自定义(使用D3.js)
  • 需要3D图表(使用Plotly)
  • 需要高级科学可视化(使用Plotly)
  • 数据集超过10000个数据点(使用带WebGL的Plotly)

Core Capabilities

核心功能

1. Basic Line Chart

1. 基础折线图

html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <canvas id="myChart" width="400" height="200"></canvas>
  <script>
    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [{
          label: 'Sales 2024',
          data: [12, 19, 3, 5, 2, 3],
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          tension: 0.1
        }]
      },
      options: {
        responsive: true,
        plugins: {
          title: {
            display: true,
            text: 'Monthly Sales'
          }
        }
      }
    });
  </script>
</body>
</html>
html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <canvas id="myChart" width="400" height="200"></canvas>
  <script>
    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [{
          label: 'Sales 2024',
          data: [12, 19, 3, 5, 2, 3],
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          tension: 0.1
        }]
      },
      options: {
        responsive: true,
        plugins: {
          title: {
            display: true,
            text: 'Monthly Sales'
          }
        }
      }
    });
  </script>
</body>
</html>

2. Bar Chart

2. 柱状图

javascript
const ctx = document.getElementById('barChart').getContext('2d');
const barChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: 'Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.6)',
        'rgba(54, 162, 235, 0.6)',
        'rgba(255, 206, 86, 0.6)',
        'rgba(75, 192, 192, 0.6)',
        'rgba(153, 102, 255, 0.6)',
        'rgba(255, 159, 64, 0.6)'
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
});
javascript
const ctx = document.getElementById('barChart').getContext('2d');
const barChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: 'Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.6)',
        'rgba(54, 162, 235, 0.6)',
        'rgba(255, 206, 86, 0.6)',
        'rgba(75, 192, 192, 0.6)',
        'rgba(153, 102, 255, 0.6)',
        'rgba(255, 159, 64, 0.6)'
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
});

3. Pie/Doughnut Chart

3. 饼图/环形图

javascript
const ctx = document.getElementById('pieChart').getContext('2d');
const pieChart = new Chart(ctx, {
  type: 'pie', // or 'doughnut'
  data: {
    labels: ['Desktop', 'Mobile', 'Tablet'],
    datasets: [{
      label: 'Device Usage',
      data: [55, 35, 10],
      backgroundColor: [
        'rgb(255, 99, 132)',
        'rgb(54, 162, 235)',
        'rgb(255, 205, 86)'
      ],
      hoverOffset: 4
    }]
  },
  options: {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: 'Device Usage Statistics'
      }
    }
  }
});
javascript
const ctx = document.getElementById('pieChart').getContext('2d');
const pieChart = new Chart(ctx, {
  type: 'pie', // or 'doughnut'
  data: {
    labels: ['Desktop', 'Mobile', 'Tablet'],
    datasets: [{
      label: 'Device Usage',
      data: [55, 35, 10],
      backgroundColor: [
        'rgb(255, 99, 132)',
        'rgb(54, 162, 235)',
        'rgb(255, 205, 86)'
      ],
      hoverOffset: 4
    }]
  },
  options: {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: 'Device Usage Statistics'
      }
    }
  }
});

Complete Examples

完整示例

Example 1: Multi-Dataset Line Chart

示例1:多数据集折线图

html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    .chart-container {
      position: relative;
      height: 400px;
      width: 80%;
      margin: auto;
    }
  </style>
</head>
<body>
  <div class="chart-container">
    <canvas id="multiLineChart"></canvas>
  </div>
  <script>
    const ctx = document.getElementById('multiLineChart').getContext('2d');
    const chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
        datasets: [
          {
            label: 'Product A',
            data: [30, 50, 45, 60],
            borderColor: 'rgb(255, 99, 132)',
            backgroundColor: 'rgba(255, 99, 132, 0.1)',
            tension: 0.4
          },
          {
            label: 'Product B',
            data: [20, 40, 55, 50],
            borderColor: 'rgb(54, 162, 235)',
            backgroundColor: 'rgba(54, 162, 235, 0.1)',
            tension: 0.4
          },
          {
            label: 'Product C',
            data: [40, 30, 35, 55],
            borderColor: 'rgb(75, 192, 192)',
            backgroundColor: 'rgba(75, 192, 192, 0.1)',
            tension: 0.4
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: {
          mode: 'index',
          intersect: false,
        },
        plugins: {
          title: {
            display: true,
            text: 'Product Sales Comparison'
          },
          legend: {
            display: true,
            position: 'top'
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            title: {
              display: true,
              text: 'Sales (units)'
            }
          },
          x: {
            title: {
              display: true,
              text: 'Time Period'
            }
          }
        }
      }
    });
  </script>
</body>
</html>
html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    .chart-container {
      position: relative;
      height: 400px;
      width: 80%;
      margin: auto;
    }
  </style>
</head>
<body>
  <div class="chart-container">
    <canvas id="multiLineChart"></canvas>
  </div>
  <script>
    const ctx = document.getElementById('multiLineChart').getContext('2d');
    const chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
        datasets: [
          {
            label: 'Product A',
            data: [30, 50, 45, 60],
            borderColor: 'rgb(255, 99, 132)',
            backgroundColor: 'rgba(255, 99, 132, 0.1)',
            tension: 0.4
          },
          {
            label: 'Product B',
            data: [20, 40, 55, 50],
            borderColor: 'rgb(54, 162, 235)',
            backgroundColor: 'rgba(54, 162, 235, 0.1)',
            tension: 0.4
          },
          {
            label: 'Product C',
            data: [40, 30, 35, 55],
            borderColor: 'rgb(75, 192, 192)',
            backgroundColor: 'rgba(75, 192, 192, 0.1)',
            tension: 0.4
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: {
          mode: 'index',
          intersect: false,
        },
        plugins: {
          title: {
            display: true,
            text: 'Product Sales Comparison'
          },
          legend: {
            display: true,
            position: 'top'
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            title: {
              display: true,
              text: 'Sales (units)'
            }
          },
          x: {
            title: {
              display: true,
              text: 'Time Period'
            }
          }
        }
      }
    });
  </script>
</body>
</html>

Example 2: Stacked Bar Chart

示例2:堆叠柱状图

javascript
const ctx = document.getElementById('stackedBar').getContext('2d');
const stackedChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Q1', 'Q2', 'Q3', 'Q4'],
    datasets: [
      {
        label: 'Revenue',
        data: [100, 120, 115, 134],
        backgroundColor: 'rgba(75, 192, 192, 0.7)',
      },
      {
        label: 'Costs',
        data: [60, 70, 65, 80],
        backgroundColor: 'rgba(255, 99, 132, 0.7)',
      },
      {
        label: 'Profit',
        data: [40, 50, 50, 54],
        backgroundColor: 'rgba(54, 162, 235, 0.7)',
      }
    ]
  },
  options: {
    responsive: true,
    scales: {
      x: {
        stacked: true,
      },
      y: {
        stacked: true,
        beginAtZero: true
      }
    },
    plugins: {
      title: {
        display: true,
        text: 'Quarterly Financial Overview'
      }
    }
  }
});
javascript
const ctx = document.getElementById('stackedBar').getContext('2d');
const stackedChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Q1', 'Q2', 'Q3', 'Q4'],
    datasets: [
      {
        label: 'Revenue',
        data: [100, 120, 115, 134],
        backgroundColor: 'rgba(75, 192, 192, 0.7)',
      },
      {
        label: 'Costs',
        data: [60, 70, 65, 80],
        backgroundColor: 'rgba(255, 99, 132, 0.7)',
      },
      {
        label: 'Profit',
        data: [40, 50, 50, 54],
        backgroundColor: 'rgba(54, 162, 235, 0.7)',
      }
    ]
  },
  options: {
    responsive: true,
    scales: {
      x: {
        stacked: true,
      },
      y: {
        stacked: true,
        beginAtZero: true
      }
    },
    plugins: {
      title: {
        display: true,
        text: 'Quarterly Financial Overview'
      }
    }
  }
});

Example 3: Radar Chart

示例3:雷达图

javascript
const ctx = document.getElementById('radarChart').getContext('2d');
const radarChart = new Chart(ctx, {
  type: 'radar',
  data: {
    labels: ['Speed', 'Reliability', 'Comfort', 'Safety', 'Efficiency'],
    datasets: [
      {
        label: 'Vehicle A',
        data: [85, 90, 70, 95, 80],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        pointBackgroundColor: 'rgb(255, 99, 132)',
      },
      {
        label: 'Vehicle B',
        data: [75, 85, 90, 85, 90],
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgb(54, 162, 235)',
        pointBackgroundColor: 'rgb(54, 162, 235)',
      }
    ]
  },
  options: {
    responsive: true,
    scales: {
      r: {
        beginAtZero: true,
        max: 100
      }
    },
    plugins: {
      title: {
        display: true,
        text: 'Vehicle Comparison'
      }
    }
  }
});
javascript
const ctx = document.getElementById('radarChart').getContext('2d');
const radarChart = new Chart(ctx, {
  type: 'radar',
  data: {
    labels: ['Speed', 'Reliability', 'Comfort', 'Safety', 'Efficiency'],
    datasets: [
      {
        label: 'Vehicle A',
        data: [85, 90, 70, 95, 80],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        pointBackgroundColor: 'rgb(255, 99, 132)',
      },
      {
        label: 'Vehicle B',
        data: [75, 85, 90, 85, 90],
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgb(54, 162, 235)',
        pointBackgroundColor: 'rgb(54, 162, 235)',
      }
    ]
  },
  options: {
    responsive: true,
    scales: {
      r: {
        beginAtZero: true,
        max: 100
      }
    },
    plugins: {
      title: {
        display: true,
        text: 'Vehicle Comparison'
      }
    }
  }
});

Example 4: Loading Data from CSV

示例4:从CSV加载数据

javascript
// Using Fetch API to load CSV
fetch('../data/sales.csv')
  .then(response => response.text())
  .then(csvText => {
    const lines = csvText.split('\n');
    const headers = lines[0].split(',');

    const labels = [];
    const data = [];

    for (let i = 1; i < lines.length; i++) {
      const values = lines[i].split(',');
      labels.push(values[0]);
      data.push(parseFloat(values[1]));
    }

    const ctx = document.getElementById('csvChart').getContext('2d');
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'Sales Data',
          data: data,
          borderColor: 'rgb(75, 192, 192)',
          tension: 0.1
        }]
      },
      options: {
        responsive: true
      }
    });
  });
javascript
// Using Fetch API to load CSV
fetch('../data/sales.csv')
  .then(response => response.text())
  .then(csvText => {
    const lines = csvText.split('\n');
    const headers = lines[0].split(',');

    const labels = [];
    const data = [];

    for (let i = 1; i < lines.length; i++) {
      const values = lines[i].split(',');
      labels.push(values[0]);
      data.push(parseFloat(values[1]));
    }

    const ctx = document.getElementById('csvChart').getContext('2d');
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'Sales Data',
          data: data,
          borderColor: 'rgb(75, 192, 192)',
          tension: 0.1
        }]
      },
      options: {
        responsive: true
      }
    });
  });

Example 5: Real-Time Updating Chart

示例5:实时更新图表

javascript
const ctx = document.getElementById('realtimeChart').getContext('2d');
const chart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: [],
    datasets: [{
      label: 'Real-time Data',
      data: [],
      borderColor: 'rgb(75, 192, 192)',
      tension: 0.1
    }]
  },
  options: {
    responsive: true,
    scales: {
      x: {
        display: true
      },
      y: {
        beginAtZero: true
      }
    },
    animation: {
      duration: 0 // Disable animation for real-time
    }
  }
});

// Update every second
let dataPoint = 0;
setInterval(() => {
  const now = new Date();
  const timeLabel = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();

  chart.data.labels.push(timeLabel);
  chart.data.datasets[0].data.push(Math.random() * 100);

  // Keep only last 20 points
  if (chart.data.labels.length > 20) {
    chart.data.labels.shift();
    chart.data.datasets[0].data.shift();
  }

  chart.update();
}, 1000);
javascript
const ctx = document.getElementById('realtimeChart').getContext('2d');
const chart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: [],
    datasets: [{
      label: 'Real-time Data',
      data: [],
      borderColor: 'rgb(75, 192, 192)',
      tension: 0.1
    }]
  },
  options: {
    responsive: true,
    scales: {
      x: {
        display: true
      },
      y: {
        beginAtZero: true
      }
    },
    animation: {
      duration: 0 // Disable animation for real-time
    }
  }
});

// Update every second
let dataPoint = 0;
setInterval(() => {
  const now = new Date();
  const timeLabel = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();

  chart.data.labels.push(timeLabel);
  chart.data.datasets[0].data.push(Math.random() * 100);

  // Keep only last 20 points
  if (chart.data.labels.length > 20) {
    chart.data.labels.shift();
    chart.data.datasets[0].data.shift();
  }

  chart.update();
}, 1000);

Example 6: Mixed Chart Types

示例6:混合图表类型

javascript
const ctx = document.getElementById('mixedChart').getContext('2d');
const mixedChart = new Chart(ctx, {
  data: {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    datasets: [
      {
        type: 'bar',
        label: 'Sales',
        data: [50, 60, 70, 80, 90],
        backgroundColor: 'rgba(54, 162, 235, 0.7)',
      },
      {
        type: 'line',
        label: 'Target',
        data: [55, 65, 75, 85, 95],
        borderColor: 'rgb(255, 99, 132)',
        fill: false
      }
    ]
  },
  options: {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Sales vs Target'
      }
    }
  }
});
javascript
const ctx = document.getElementById('mixedChart').getContext('2d');
const mixedChart = new Chart(ctx, {
  data: {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    datasets: [
      {
        type: 'bar',
        label: 'Sales',
        data: [50, 60, 70, 80, 90],
        backgroundColor: 'rgba(54, 162, 235, 0.7)',
      },
      {
        type: 'line',
        label: 'Target',
        data: [55, 65, 75, 85, 95],
        borderColor: 'rgb(255, 99, 132)',
        fill: false
      }
    ]
  },
  options: {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Sales vs Target'
      }
    }
  }
});

Best Practices

最佳实践

1. Use Responsive Containers

1. 使用响应式容器

html
<div style="position: relative; height: 400px; width: 100%;">
  <canvas id="myChart"></canvas>
</div>
javascript
options: {
  responsive: true,
  maintainAspectRatio: false
}
html
<div style="position: relative; height: 400px; width: 100%;">
  <canvas id="myChart"></canvas>
</div>
javascript
options: {
  responsive: true,
  maintainAspectRatio: false
}

2. Destroy Charts Before Recreating

2. 重建前销毁现有图表

javascript
let myChart;

function createChart(data) {
  // Destroy existing chart
  if (myChart) {
    myChart.destroy();
  }

  const ctx = document.getElementById('myChart').getContext('2d');
  myChart = new Chart(ctx, {
    type: 'line',
    data: data
  });
}
javascript
let myChart;

function createChart(data) {
  // Destroy existing chart
  if (myChart) {
    myChart.destroy();
  }

  const ctx = document.getElementById('myChart').getContext('2d');
  myChart = new Chart(ctx, {
    type: 'line',
    data: data
  });
}

3. Use Plugins for Extended Functionality

3. 使用插件扩展功能

javascript
// Example: Chart.js Data Labels Plugin
import ChartDataLabels from 'chartjs-plugin-datalabels';

const chart = new Chart(ctx, {
  plugins: [ChartDataLabels],
  data: {...},
  options: {
    plugins: {
      datalabels: {
        color: '#fff',
        display: true
      }
    }
  }
});
javascript
// Example: Chart.js Data Labels Plugin
import ChartDataLabels from 'chartjs-plugin-datalabels';

const chart = new Chart(ctx, {
  plugins: [ChartDataLabels],
  data: {...},
  options: {
    plugins: {
      datalabels: {
        color: '#fff',
        display: true
      }
    }
  }
});

4. Optimize for Performance

4. 性能优化

javascript
options: {
  // Disable animations for large datasets
  animation: {
    duration: 0
  },
  // Use decimation for large datasets
  parsing: false,
  normalized: true
}
javascript
options: {
  // Disable animations for large datasets
  animation: {
    duration: 0
  },
  // Use decimation for large datasets
  parsing: false,
  normalized: true
}

Available Chart Types

可用图表类型

  1. Line - Trend analysis, time series
  2. Bar - Comparisons, categorical data
  3. Pie - Proportions, percentages
  4. Doughnut - Like pie, with center hole
  5. Radar - Multivariate data
  6. Polar Area - Similar to pie with variable radii
  7. Bubble - 3-dimensional data (x, y, size)
  8. Scatter - Correlation analysis
  1. 折线图 - 趋势分析、时间序列
  2. 柱状图 - 对比分析、分类数据
  3. 饼图 - 比例、百分比
  4. 环形图 - 类似饼图,带中心空洞
  5. 雷达图 - 多变量数据
  6. 极地区域图 - 类似饼图,但半径可变
  7. 气泡图 - 三维数据(x、y、大小)
  8. 散点图 - 相关性分析

Common Customizations

常见自定义设置

Custom Colors

自定义颜色

javascript
const colors = [
  '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)'
];
javascript
const colors = [
  '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)'
];

Custom Tooltips

自定义提示框

javascript
options: {
  plugins: {
    tooltip: {
      callbacks: {
        label: function(context) {
          let label = context.dataset.label || '';
          if (label) {
            label += ': ';
          }
          label += '$' + context.parsed.y.toFixed(2);
          return label;
        }
      }
    }
  }
}
javascript
options: {
  plugins: {
    tooltip: {
      callbacks: {
        label: function(context) {
          let label = context.dataset.label || '';
          if (label) {
            label += ': ';
          }
          label += '$' + context.parsed.y.toFixed(2);
          return label;
        }
      }
    }
  }
}

Custom Legends

自定义图例

javascript
options: {
  plugins: {
    legend: {
      position: 'bottom',
      labels: {
        font: {
          size: 14
        },
        usePointStyle: true
      }
    }
  }
}
javascript
options: {
  plugins: {
    legend: {
      position: 'bottom',
      labels: {
        font: {
          size: 14
        },
        usePointStyle: true
      }
    }
  }
}

Installation

安装方式

CDN (Quick Start)

CDN(快速开始)

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

NPM

NPM

bash
npm install chart.js
javascript
import Chart from 'chart.js/auto';
bash
npm install chart.js
javascript
import Chart from 'chart.js/auto';

ES Modules

ES模块

html
<script type="module">
  import Chart from 'https://cdn.jsdelivr.net/npm/chart.js@4/+esm';

  const ctx = document.getElementById('myChart');
  new Chart(ctx, {...});
</script>
html
<script type="module">
  import Chart from 'https://cdn.jsdelivr.net/npm/chart.js@4/+esm';

  const ctx = document.getElementById('myChart');
  new Chart(ctx, {...});
</script>

Popular Plugins

热门插件

Chart.js Zoom Plugin

Chart.js 缩放插件

bash
npm install chartjs-plugin-zoom
javascript
import zoomPlugin from 'chartjs-plugin-zoom';
Chart.register(zoomPlugin);

options: {
  plugins: {
    zoom: {
      zoom: {
        wheel: { enabled: true },
        pinch: { enabled: true },
        mode: 'xy'
      }
    }
  }
}
bash
npm install chartjs-plugin-zoom
javascript
import zoomPlugin from 'chartjs-plugin-zoom';
Chart.register(zoomPlugin);

options: {
  plugins: {
    zoom: {
      zoom: {
        wheel: { enabled: true },
        pinch: { enabled: true },
        mode: 'xy'
      }
    }
  }
}

Chart.js Annotation Plugin

Chart.js 注释插件

bash
npm install chartjs-plugin-annotation
bash
npm install chartjs-plugin-annotation

Chart.js Data Labels

Chart.js 数据标签

bash
npm install chartjs-plugin-datalabels
bash
npm install chartjs-plugin-datalabels

Integration Examples

集成示例

With React

与React集成

javascript
import { useEffect, useRef } from 'react';
import Chart from 'chart.js/auto';

function ChartComponent({ data }) {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);

  useEffect(() => {
    if (chartInstance.current) {
      chartInstance.current.destroy();
    }

    const ctx = chartRef.current.getContext('2d');
    chartInstance.current = new Chart(ctx, {
      type: 'line',
      data: data,
      options: { responsive: true }
    });

    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }
    };
  }, [data]);

  return <canvas ref={chartRef} />;
}
javascript
import { useEffect, useRef } from 'react';
import Chart from 'chart.js/auto';

function ChartComponent({ data }) {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);

  useEffect(() => {
    if (chartInstance.current) {
      chartInstance.current.destroy();
    }

    const ctx = chartRef.current.getContext('2d');
    chartInstance.current = new Chart(ctx, {
      type: 'line',
      data: data,
      options: { responsive: true }
    });

    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }
    };
  }, [data]);

  return <canvas ref={chartRef} />;
}

With Vue

与Vue集成

vue
<template>
  <canvas ref="chartCanvas"></canvas>
</template>

<script>
import Chart from 'chart.js/auto';

export default {
  props: ['chartData'],
  mounted() {
    this.renderChart();
  },
  methods: {
    renderChart() {
      const ctx = this.$refs.chartCanvas.getContext('2d');
      new Chart(ctx, {
        type: 'bar',
        data: this.chartData,
        options: { responsive: true }
      });
    }
  }
};
</script>
vue
<template>
  <canvas ref="chartCanvas"></canvas>
</template>

<script>
import Chart from 'chart.js/auto';

export default {
  props: ['chartData'],
  mounted() {
    this.renderChart();
  },
  methods: {
    renderChart() {
      const ctx = this.$refs.chartCanvas.getContext('2d');
      new Chart(ctx, {
        type: 'bar',
        data: this.chartData,
        options: { responsive: true }
      });
    }
  }
};
</script>

Resources

参考资源

Performance Tips

性能优化技巧

  1. Disable animations for large datasets
  2. Use decimation to reduce data points
  3. Limit updates - batch chart updates
  4. Destroy unused charts - free memory
  5. Use canvas size wisely - larger canvas = slower rendering

Use this skill for quick, simple charts that look great with minimal configuration!
  1. 禁用动画 - 针对大型数据集
  2. 使用数据抽取 - 减少数据点数量
  3. 限制更新频率 - 批量更新图表
  4. 销毁未使用的图表 - 释放内存
  5. 合理设置画布尺寸 - 画布越大,渲染越慢

使用该技能快速创建美观、配置简单的图表!