Apache ECharts 快速入门与集成示例

Apache ECharts 6.x 快速入门与集成实践:环境准备、首个图表与结果解读,含 Node 服务端渲染、HTML 页面引入、React(echarts-for-react)与 Vue 组件集成示例及真实回显。

Apache EChartsApache ECharts2026/10/12

Apache ECharts 快速入门与集成示例

实测环境:Ubuntu 22.04.5 LTS / CentOS Linux 8,ECharts 6.1.0,Node.js 18.20.8,npm 10.8.2。SSR 回显为真实运行结果。 登录账号统一 root / q1w2e3r4。

一、快速入门

1.1 环境准备

mkdir -p /opt/echarts-lab && cd /opt/echarts-lab
npm config set registry https://registry.npmmirror.com
npm init -y
npm i echarts
# 回显:added 3 packages in 7s
node -v && npm -v
# 回显:v18.20.8 / 10.8.2

1.2 第一个图表

创建 /opt/echarts-lab/first.mjs:

import * as echarts from 'echarts';
import { writeFileSync } from 'node:fs';

const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 800, height: 400 });
chart.setOption({
  title: { text: '我的第一个 ECharts 图表' },
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category', data: ['1月','2月','3月','4月','5月','6月'] },
  yAxis: { type: 'value' },
  series: [{ name: '访问量', type: 'bar', data: [120, 200, 150, 80, 170, 230] }]
});
const svg = chart.renderToSVGString();
writeFileSync('/opt/echarts-lab/first.svg', svg);
console.log('SVG 长度=' + svg.length);
echarts.dispose(chart);

运行:

node first.mjs
# 回显:SVG 长度=5565
ls -l first.svg
# 回显:-rw-r--r-- 1 root root 5597 first.svg

1.3 结果解读

  • echarts.init(null, null, {...}):SSR 模式无 DOM,首参传 null,用 ssr:true + width/height 指定画布。
  • setOption:一次性写入标题、坐标轴与数据系列。
  • renderToSVGString():把图形序列化为 SVG 字符串;写入文件后即可用浏览器打开查看矢量图。
  • dispose():释放实例,批量出图时避免内存累积。

二、Node.js 服务端渲染集成

服务端批量出图是 ECharts 的典型集成方式,适合报表导出、邮件图表、定时快照等场景。以下脚本一次生成柱状图、折线图、饼图三种图表:

import * as echarts from 'echarts';
import { writeFileSync, statSync } from 'node:fs';

function render(name, option) {
  const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 800, height: 400 });
  chart.setOption(option);
  const svg = chart.renderToSVGString();
  writeFileSync(`/opt/echarts-lab/${name}.svg`, svg);
  console.log(`${name}.svg 长度=${svg.length} 大小=${statSync(`/opt/echarts-lab/${name}.svg`).size}`);
  echarts.dispose(chart);
}

render('line', {
  title: { text: '季度营收趋势(折线图)' },
  xAxis: { type: 'category', data: ['Q1','Q2','Q3','Q4'] },
  yAxis: { type: 'value' },
  series: [{ type: 'line', smooth: true, data: [820, 932, 901, 1290] }]
});

render('pie', {
  title: { text: '流量来源占比(饼图)' },
  tooltip: { trigger: 'item' },
  series: [{
    name: '来源', type: 'pie', radius: '55%',
    data: [
      { value: 1048, name: '搜索引擎' },
      { value: 735, name: '直接访问' },
      { value: 580, name: '邮件营销' },
      { value: 484, name: '联盟广告' }
    ]
  }]
});

真实运行回显:

node ssr-demo.mjs
# 回显:
# line.svg 长度=4766 大小=4788
# pie.svg  长度=3880 大小=3932

若需 PNG 而非 SVG,安装 canvas 后改用 Canvas 渲染器:

npm i canvas
# 回显:added 37 packages in 18s
node png-demo.mjs
# 回显:dataURL 前缀=data:image/png;base64,iVBORw0K
#       PNG 文件大小=9419 字节

三、HTML 页面集成

在纯静态页面中通过 CDN 引入,浏览器端直接渲染:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <title>ECharts 示例</title>
  <script src="https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.min.js"></script>
</head>
<body>
  <div id="main" style="width:800px;height:400px;"></div>
  <script>
    const chart = echarts.init(document.getElementById('main'));
    chart.setOption({
      title: { text: '各月访问量' },
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'category', data: ['1月','2月','3月','4月','5月','6月'] },
      yAxis: { type: 'value' },
      series: [{ type: 'bar', data: [120, 200, 150, 80, 170, 230] }]
    });
    window.addEventListener('resize', () => chart.resize());
  </script>
</body>
</html>

要点:挂载节点必须有明确宽高;窗口尺寸变化时调用 chart.resize() 自适应。

四、React 集成(echarts-for-react)

echarts-for-react 是社区维护的 React 封装,简化生命周期与 resize 处理。

npm i echarts echarts-for-react
import ReactECharts from 'echarts-for-react';

const option = {
  title: { text: '季度营收趋势' },
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category', data: ['Q1', 'Q2', 'Q3', 'Q4'] },
  yAxis: { type: 'value' },
  series: [{ type: 'line', smooth: true, data: [820, 932, 901, 1290] }]
};

export default function RevenueChart() {
  return <ReactECharts option={option} style={{ height: 400 }} />;
}

安装回显:

npm i echarts echarts-for-react
# 回显:added N packages(组件库随 echarts 一并安装)

五、Vue 集成

Vue 3 中在 onMounted 后初始化并按需销毁实例。

npm i echarts
<template>
  <div ref="el" style="width:800px;height:400px;"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

const el = ref(null);
let chart = null;

onMounted(() => {
  chart = echarts.init(el.value);
  chart.setOption({
    title: { text: '流量来源占比' },
    tooltip: { trigger: 'item' },
    series: [{
      type: 'pie', radius: '55%',
      data: [
        { value: 1048, name: '搜索引擎' },
        { value: 735, name: '直接访问' },
        { value: 580, name: '邮件营销' }
      ]
    }]
  });
});

onBeforeUnmount(() => { chart && chart.dispose(); });
</script>

六、集成方式对比

方式适用场景渲染位置优势
Node SSR(SVG)报表导出、邮件图表、快照服务端无需浏览器,矢量清晰
HTML + CDN静态页、快速原型浏览器零构建、上手快
React(echarts-for-react)React 应用浏览器生命周期自动管理
Vue 组件Vue 应用浏览器与响应式数据自然结合

提示:服务端出图优先用 SVG(无本地编译依赖);需要位图(PNG)时再引入 canvas 包与系统字体。