Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02212e9ef7 | ||
|
|
df2981889e | ||
|
|
d4ce91efd1 | ||
|
|
ad3e74e391 |
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
logs/
|
||||
*.png
|
||||
*.svg
|
||||
@@ -0,0 +1,310 @@
|
||||
# 📡 数据可视化图表生成器 - API 文档
|
||||
|
||||
> 版本:v1.1.0 | 基础地址:`http://192.168.0.101:16016`
|
||||
|
||||
---
|
||||
|
||||
## 接口总览
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| POST | `/api/chart` | 生成图表图片(JSON body,推荐) |
|
||||
| GET | `/api/chart` | 生成图表图片(URL 参数) |
|
||||
| GET | `/api/health` | 健康检查 |
|
||||
| GET | `/api/docs` | 返回本文档(JSON) |
|
||||
|
||||
---
|
||||
|
||||
## 1. POST /api/chart(推荐)
|
||||
|
||||
通过 JSON 请求体生成图表,返回 PNG 图片。
|
||||
|
||||
### 请求
|
||||
|
||||
```
|
||||
POST /api/chart
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
### 参数说明
|
||||
|
||||
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|
||||
|------|------|:----:|--------|------|
|
||||
| `data` | string | ✅ | — | CSV 格式数据,`\n` 换行,第一行表头,第一列横坐标 |
|
||||
| `chartType` | string | — | `bar` | 图表类型:`bar` / `line` / `bar-line` |
|
||||
| `title` | string | — | `""` | 图表标题 |
|
||||
| `theme` | string | — | `default` | 主题风格:`default` / `dark` / `macarons` / `gradient` / `retro` |
|
||||
| `showLegend` | boolean | — | `true` | 显示图例 |
|
||||
| `showGrid` | boolean | — | `true` | 显示网格线 |
|
||||
| `showLabel` | boolean | — | `false` | 显示数据标签 |
|
||||
| `stackMode` | boolean | — | `false` | 堆叠模式 |
|
||||
| `smoothLine` | boolean | — | `true` | 折线平滑 |
|
||||
| `enableSplit` | boolean | — | `false` | 启用区域分割 |
|
||||
| `splitIndex` | number | — | `3` | 分割位置(第几个数据后分割) |
|
||||
| `leftLabel` | string | — | `"左侧"` | 左侧区域标签 |
|
||||
| `rightLabel` | string | — | `"右侧"` | 右侧区域标签 |
|
||||
| `splitStyle` | string | — | `"solid"` | 分割线样式:`solid` / `dashed` / `dotted` |
|
||||
| `width` | number | — | `800` | 图片宽度(px) |
|
||||
| `height` | number | — | `500` | 图片高度(px) |
|
||||
| `pixelRatio` | number | — | `2` | 像素倍率(越大越清晰) |
|
||||
|
||||
### 返回
|
||||
|
||||
- **Content-Type:** `image/png`
|
||||
- **响应头:**
|
||||
- `X-Chart-Width` — 图片宽度
|
||||
- `X-Chart-Height` — 图片高度
|
||||
- `X-Chart-Pixel-Ratio` — 像素倍率
|
||||
|
||||
### curl 示例
|
||||
|
||||
**基础柱状图:**
|
||||
```bash
|
||||
curl -X POST http://192.168.0.101:16016/api/chart \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"data": "产品, Q1, Q2, Q3, Q4\n手机, 1200, 1800, 2100, 2500\n平板, 800, 950, 1100, 1300\n笔记本, 600, 750, 900, 1050",
|
||||
"chartType": "bar",
|
||||
"title": "季度销售对比"
|
||||
}' -o chart.png
|
||||
```
|
||||
|
||||
**深色主题折线图 + 数据标签:**
|
||||
```bash
|
||||
curl -X POST http://192.168.0.101:16016/api/chart \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"data": "月份, 营收(万), 利润(万), 用户(千)\n1月, 500, 80, 50\n2月, 680, 120, 85\n3月, 820, 160, 130\n4月, 1050, 230, 200\n5月, 1380, 350, 320",
|
||||
"chartType": "line",
|
||||
"title": "年度增长趋势",
|
||||
"theme": "dark",
|
||||
"showLabel": true,
|
||||
"width": 900,
|
||||
"height": 500
|
||||
}' -o trend.png
|
||||
```
|
||||
|
||||
**区域分割对比图:**
|
||||
```bash
|
||||
curl -X POST http://192.168.0.101:16016/api/chart \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"data": "月份, 方案A, 方案B\n1月, 85, 78\n2月, 88, 82\n3月, 92, 88\n4月, 90, 95\n5月, 95, 98\n6月, 98, 102",
|
||||
"chartType": "bar",
|
||||
"title": "方案对比",
|
||||
"theme": "gradient",
|
||||
"enableSplit": true,
|
||||
"splitIndex": 3,
|
||||
"leftLabel": "上半年",
|
||||
"rightLabel": "下半年",
|
||||
"splitStyle": "dashed"
|
||||
}' -o compare.png
|
||||
```
|
||||
|
||||
**堆叠柱状图:**
|
||||
```bash
|
||||
curl -X POST http://192.168.0.101:16016/api/chart \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"data": "季度, 线上, 线下, 批发\nQ1, 300, 200, 150\nQ2, 450, 280, 200\nQ3, 520, 350, 180\nQ4, 680, 400, 250",
|
||||
"chartType": "bar",
|
||||
"title": "渠道销售分布",
|
||||
"stackMode": true,
|
||||
"theme": "macarons"
|
||||
}' -o stack.png
|
||||
```
|
||||
|
||||
**高分辨率大图:**
|
||||
```bash
|
||||
curl -X POST http://192.168.0.101:16016/api/chart \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"data": "产品, 2023, 2024, 2025\nA, 100, 200, 300\nB, 150, 250, 350",
|
||||
"width": 1600,
|
||||
"height": 900,
|
||||
"pixelRatio": 3
|
||||
}' -o hd-chart.png
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. GET /api/chart
|
||||
|
||||
通过 URL 参数生成图表,适合简单场景或直接在浏览器中使用。
|
||||
|
||||
### 参数
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `data` | CSV 数据(换行用 `\n` 表示,需 URL 编码) |
|
||||
| `type` | 图表类型(bar / line / bar-line) |
|
||||
| `title` | 图表标题 |
|
||||
| `theme` | 主题风格 |
|
||||
| `width` | 图片宽度 |
|
||||
| `height` | 图片高度 |
|
||||
|
||||
### curl 示例
|
||||
|
||||
```bash
|
||||
curl "http://192.168.0.101:16016/api/chart?data=%E4%BA%A7%E5%93%81,Q1,Q2%0A%E6%89%8B%E6%9C%BA,100,200%0A%E5%B9%B3%E6%9D%BF,150,250&type=bar&title=%E6%B5%8B%E8%AF%95" -o chart.png
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. GET /api/health
|
||||
|
||||
健康检查。
|
||||
|
||||
```bash
|
||||
curl http://192.168.0.101:16016/api/health
|
||||
```
|
||||
|
||||
返回:
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"service": "data-chart-tool",
|
||||
"version": "1.1.0",
|
||||
"endpoints": {
|
||||
"POST /api/chart": "生成图表图片(JSON body)",
|
||||
"GET /api/chart": "生成图表图片(URL 参数)",
|
||||
"GET /api/health": "健康检查"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 数据格式说明
|
||||
|
||||
CSV 格式,规则:
|
||||
|
||||
1. **第一行**:表头(系列名称)
|
||||
2. **第一列**:横坐标值
|
||||
3. **其余单元格**:数值
|
||||
4. **分隔符**:逗号(自动识别制表符和 `|`)
|
||||
|
||||
```
|
||||
类别, 系列1, 系列2, 系列3
|
||||
A, 10, 20, 30
|
||||
B, 15, 25, 35
|
||||
C, 20, 30, 40
|
||||
```
|
||||
|
||||
在 JSON 中用 `\n` 表示换行:
|
||||
```json
|
||||
{
|
||||
"data": "类别, 系列1, 系列2, 系列3\nA, 10, 20, 30\nB, 15, 25, 35\nC, 20, 30, 40"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 各语言调用示例
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
resp = requests.post('http://192.168.0.101:16016/api/chart', json={
|
||||
"data": "月份, 营收, 利润\n1月, 500, 80\n2月, 680, 120\n3月, 820, 160",
|
||||
"chartType": "line",
|
||||
"title": "增长趋势",
|
||||
"theme": "dark",
|
||||
"showLabel": True,
|
||||
"width": 900,
|
||||
"height": 500
|
||||
})
|
||||
|
||||
with open('chart.png', 'wb') as f:
|
||||
f.write(resp.content)
|
||||
|
||||
print(f"图片大小: {len(resp.content)} bytes")
|
||||
```
|
||||
|
||||
### JavaScript (Node.js)
|
||||
|
||||
```javascript
|
||||
const fetch = require('node-fetch');
|
||||
const fs = require('fs');
|
||||
|
||||
const resp = await fetch('http://192.168.0.101:16016/api/chart', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
data: "产品, Q1, Q2\n手机, 1200, 2500\n平板, 800, 1300",
|
||||
chartType: "bar",
|
||||
title: "销售对比",
|
||||
width: 800,
|
||||
height: 500
|
||||
})
|
||||
});
|
||||
|
||||
const buffer = await resp.buffer();
|
||||
fs.writeFileSync('chart.png', buffer);
|
||||
```
|
||||
|
||||
### JavaScript (浏览器 fetch)
|
||||
|
||||
```javascript
|
||||
const resp = await fetch('http://192.168.0.101:16016/api/chart', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
data: "产品, Q1, Q2\n手机, 1200, 2500\n平板, 800, 1300",
|
||||
chartType: "bar",
|
||||
title: "销售对比"
|
||||
})
|
||||
});
|
||||
|
||||
const blob = await resp.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const img = document.createElement('img');
|
||||
img.src = url;
|
||||
document.body.appendChild(img);
|
||||
```
|
||||
|
||||
### Shell (保存到文件)
|
||||
|
||||
```bash
|
||||
curl -X POST http://192.168.0.101:16016/api/chart \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"data":"A,B\n1,2\n3,4","chartType":"bar"}' \
|
||||
-o chart.png
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 主题预览
|
||||
|
||||
| 主题 | 说明 | 适用场景 |
|
||||
|------|------|----------|
|
||||
| `default` | 经典蓝绿配色 | 通用 |
|
||||
| `dark` | 深色背景 + 高亮色 | 大屏展示、PPT |
|
||||
| `macarons` | 柔和马卡龙色 | 清新风格 |
|
||||
| `gradient` | 渐变色 + 圆角柱 | 现代感设计 |
|
||||
| `retro` | 复古低饱和度 | 文艺风格 |
|
||||
|
||||
---
|
||||
|
||||
## 错误处理
|
||||
|
||||
请求失败时返回 JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "缺少 data 参数(CSV 格式数据)"
|
||||
}
|
||||
```
|
||||
|
||||
常见错误:
|
||||
|
||||
| HTTP 状态码 | 原因 |
|
||||
|:-----------:|------|
|
||||
| 400 | 缺少 `data` 参数或数据格式错误 |
|
||||
| 500 | 服务端渲染异常 |
|
||||
|
||||
---
|
||||
|
||||
*文档更新时间:2026-07-16*
|
||||
@@ -0,0 +1,196 @@
|
||||
# 📊 数据可视化图表生成器
|
||||
|
||||
一个简洁强大的数据可视化工具,支持 **Web UI** 和 **API** 两种方式生成精美的对比图表图片。
|
||||
|
||||

|
||||

|
||||
|
||||
## ✨ 功能特性
|
||||
|
||||
### 📈 图表类型
|
||||
- **柱状图** - 支持单系列/多系列对比
|
||||
- **折线图** - 支持平滑曲线、面积填充
|
||||
- **混合图** - 柱状图+折线图组合展示
|
||||
|
||||
### 🎨 自定义配置
|
||||
- **主题风格** - 5种预设主题(默认/深色/马卡龙/渐变/复古)
|
||||
- **颜色自定义** - 每个系列可单独设置颜色
|
||||
- **顺序调整** - 拖拽即可调整系列显示顺序(Web UI)
|
||||
- **显示选项** - 图例、网格线、数据标签、堆叠模式等
|
||||
|
||||
### 📐 区域分割
|
||||
- 支持左右区域分割,适合对比分析(如:2023年 vs 2024年)
|
||||
- 可自定义分割线样式(实线/虚线/点线)
|
||||
- 自动标注左右区域标签
|
||||
|
||||
### 📡 API 接口
|
||||
- **POST /api/chart** - JSON 请求体生成图表(完整参数支持)
|
||||
- **GET /api/chart** - URL 参数生成图表(简单场景)
|
||||
- 返回 PNG 图片,支持自定义分辨率和像素倍率
|
||||
|
||||
### 📥 导出功能
|
||||
- Web UI 导出 PNG(2倍分辨率)
|
||||
- API 直接返回 PNG 图片流
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 启动服务
|
||||
|
||||
```bash
|
||||
cd data-chart-tool
|
||||
npm install
|
||||
npm start
|
||||
# 或
|
||||
node server.js
|
||||
```
|
||||
|
||||
服务默认运行在 `16016` 端口,可通过环境变量修改:
|
||||
|
||||
```bash
|
||||
PORT=8080 node server.js
|
||||
```
|
||||
|
||||
### Web UI
|
||||
|
||||
浏览器访问 `http://localhost:16016` 即可使用可视化界面。
|
||||
|
||||
### API 调用
|
||||
|
||||
#### POST 方式(推荐)
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:16016/api/chart \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"data": "产品, Q1, Q2, Q3, Q4\n手机, 1200, 1800, 2100, 2500\n平板, 800, 950, 1100, 1300",
|
||||
"chartType": "bar",
|
||||
"title": "季度销售对比",
|
||||
"theme": "default",
|
||||
"width": 800,
|
||||
"height": 500
|
||||
}' -o chart.png
|
||||
```
|
||||
|
||||
#### GET 方式
|
||||
|
||||
```bash
|
||||
curl "http://localhost:16016/api/chart?data=产品,Q1,Q2\n手机,100,200\n平板,150,250&type=bar&title=测试" -o chart.png
|
||||
```
|
||||
|
||||
#### Python 调用示例
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
resp = requests.post('http://localhost:16016/api/chart', json={
|
||||
"data": "月份, 营收, 利润\n1月, 500, 80\n2月, 680, 120\n3月, 820, 160",
|
||||
"chartType": "line",
|
||||
"title": "增长趋势",
|
||||
"theme": "dark",
|
||||
"showLabel": True,
|
||||
"width": 900,
|
||||
"height": 500
|
||||
})
|
||||
|
||||
with open('chart.png', 'wb') as f:
|
||||
f.write(resp.content)
|
||||
```
|
||||
|
||||
## 📡 API 文档
|
||||
|
||||
### POST /api/chart
|
||||
|
||||
通过 JSON 请求体生成图表图片。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|
||||
|------|------|------|--------|------|
|
||||
| data | string | ✅ | - | CSV 格式数据(`\n` 换行,第一行表头,第一列横坐标) |
|
||||
| chartType | string | - | bar | 图表类型:`bar` / `line` / `bar-line` |
|
||||
| title | string | - | "" | 图表标题 |
|
||||
| theme | string | - | default | 主题:`default` / `dark` / `macarons` / `gradient` / `retro` |
|
||||
| showLegend | boolean | - | true | 是否显示图例 |
|
||||
| showGrid | boolean | - | true | 是否显示网格线 |
|
||||
| showLabel | boolean | - | false | 是否显示数据标签 |
|
||||
| stackMode | boolean | - | false | 是否堆叠模式 |
|
||||
| smoothLine | boolean | - | true | 折线图是否平滑 |
|
||||
| enableSplit | boolean | - | false | 是否启用区域分割 |
|
||||
| splitIndex | number | - | 3 | 分割位置索引 |
|
||||
| leftLabel | string | - | "左侧" | 左侧区域标签 |
|
||||
| rightLabel | string | - | "右侧" | 右侧区域标签 |
|
||||
| splitStyle | string | - | "solid" | 分割线样式:`solid` / `dashed` / `dotted` |
|
||||
| width | number | - | 800 | 图片宽度(px) |
|
||||
| height | number | - | 500 | 图片高度(px) |
|
||||
| pixelRatio | number | - | 2 | 像素倍率(清晰度) |
|
||||
|
||||
**返回:** `image/png` 二进制流
|
||||
|
||||
### GET /api/chart
|
||||
|
||||
通过 URL 参数生成图表(适合简单场景)。
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| data | CSV 数据(换行用 `\n` 表示) |
|
||||
| type | 图表类型 |
|
||||
| title | 图表标题 |
|
||||
| theme | 主题风格 |
|
||||
| width | 图片宽度 |
|
||||
| height | 图片高度 |
|
||||
|
||||
### GET /api/health
|
||||
|
||||
健康检查,返回服务状态。
|
||||
|
||||
### GET /api/docs
|
||||
|
||||
返回 API 文档(JSON 格式)。
|
||||
|
||||
## 📝 数据格式
|
||||
|
||||
第一行为**表头**(系列名称),第一列为**横坐标值**,支持逗号、制表符分隔:
|
||||
|
||||
```
|
||||
类别, 系列1, 系列2, 系列3
|
||||
A, 10, 20, 30
|
||||
B, 15, 25, 35
|
||||
C, 20, 30, 40
|
||||
```
|
||||
|
||||
## 🛠️ 技术栈
|
||||
|
||||
- **ECharts 5.5.0** - 图表渲染引擎
|
||||
- **@napi-rs/canvas** - Node.js 服务端 Canvas 渲染
|
||||
- **Express** - Web 服务框架
|
||||
- **原生 HTML/CSS/JS** - 前端无框架依赖
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
```
|
||||
data-chart-tool/
|
||||
├── server.js # Node.js 后端(API 服务)
|
||||
├── app.js # 前端核心逻辑
|
||||
├── index.html # Web UI 主页面
|
||||
├── style.css # 样式文件
|
||||
├── package.json # 依赖管理
|
||||
└── README.md # 项目说明
|
||||
```
|
||||
|
||||
## 🔧 开发计划
|
||||
|
||||
- [x] 支持 API 生成图表图片
|
||||
- [ ] 支持饼图、雷达图等更多图表类型
|
||||
- [ ] 支持从 Excel/CSV 文件导入
|
||||
- [ ] 支持数据编辑和实时预览
|
||||
- [ ] 添加更多主题风格
|
||||
- [ ] 支持图表模板保存和分享
|
||||
- [ ] 支持 SVG 格式服务端导出
|
||||
|
||||
## 📄 License
|
||||
|
||||
MIT License
|
||||
|
||||
---
|
||||
|
||||
Made with ❤️ by 黄庄4号程序员
|
||||
Generated
+1146
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "data-chart-tool",
|
||||
"version": "1.1.0",
|
||||
"description": "数据可视化图表生成器 - 支持 Web UI 和 API 生成图表图片",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "node server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.18.2",
|
||||
"echarts": "^5.5.0",
|
||||
"@napi-rs/canvas": "^0.1.58",
|
||||
"cors": "^2.8.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const { createCanvas } = require('@napi-rs/canvas');
|
||||
const echarts = require('echarts');
|
||||
const path = require('path');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 16016;
|
||||
|
||||
// 中间件
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
|
||||
|
||||
// 静态文件(前端页面)
|
||||
app.use(express.static(path.join(__dirname)));
|
||||
|
||||
// ===== 预设颜色方案 =====
|
||||
const colorPalettes = {
|
||||
default: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
|
||||
dark: ['#4fc3f7', '#81c784', '#fff176', '#ff8a65', '#ba68c8', '#4dd0e1', '#ffab91', '#aed581', '#f48fb1'],
|
||||
macarons: ['#2ec7c9', '#b6a2de', '#5ab1ef', '#ffb980', '#d87a80', '#8d98b3', '#e5cf0d', '#97b552', '#95706d'],
|
||||
gradient: ['#7f7fd5', '#86a8e7', '#91eae4', '#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff', '#5f27cd'],
|
||||
retro: ['#d4a5a5', '#95b9c7', '#f6e8c3', '#dfceb4', '#a4c3b5', '#c9b1ff', '#f5c7b8', '#b8d4e3', '#e8c8a0']
|
||||
};
|
||||
|
||||
// ===== 数据解析(与前端一致) =====
|
||||
function parseData(rawText) {
|
||||
const lines = rawText.trim().split('\n').filter(l => l.trim());
|
||||
if (lines.length < 2) {
|
||||
throw new Error('数据至少需要包含表头和一行数据');
|
||||
}
|
||||
|
||||
// 自动检测分隔符
|
||||
let delimiter = ',';
|
||||
if (lines[0].includes('\t')) {
|
||||
delimiter = '\t';
|
||||
} else if (lines[0].split('|').length > lines[0].split(',').length) {
|
||||
delimiter = '|';
|
||||
}
|
||||
|
||||
const rows = lines.map(line => {
|
||||
return line.split(delimiter).map(cell => cell.trim());
|
||||
});
|
||||
|
||||
const headers = rows[0];
|
||||
const categories = [];
|
||||
const seriesData = {};
|
||||
|
||||
for (let i = 1; i < headers.length; i++) {
|
||||
seriesData[headers[i]] = [];
|
||||
}
|
||||
|
||||
for (let i = 1; i < rows.length; i++) {
|
||||
categories.push(rows[i][0]);
|
||||
for (let j = 1; j < rows[i].length && j < headers.length; j++) {
|
||||
const val = parseFloat(rows[i][j]);
|
||||
seriesData[headers[j]].push(isNaN(val) ? 0 : val);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
categories,
|
||||
seriesNames: headers.slice(1),
|
||||
seriesData
|
||||
};
|
||||
}
|
||||
|
||||
// ===== 颜色工具 =====
|
||||
function adjustColor(hex, amount) {
|
||||
hex = hex.replace('#', '');
|
||||
const num = parseInt(hex, 16);
|
||||
let r = Math.min(255, ((num >> 16) & 0xff) + amount);
|
||||
let g = Math.min(255, ((num >> 8) & 0xff) + amount);
|
||||
let b = Math.min(255, (num & 0xff) + amount);
|
||||
return `rgb(${r},${g},${b})`;
|
||||
}
|
||||
|
||||
// ===== 构建 ECharts option =====
|
||||
function buildChartOption(params) {
|
||||
const {
|
||||
data,
|
||||
chartType = 'bar',
|
||||
title = '',
|
||||
theme = 'default',
|
||||
showLegend = true,
|
||||
showGrid = true,
|
||||
showLabel = false,
|
||||
stackMode = false,
|
||||
smoothLine = true,
|
||||
enableSplit = false,
|
||||
splitIndex = 3,
|
||||
leftLabel = '左侧',
|
||||
rightLabel = '右侧',
|
||||
splitStyle = 'solid',
|
||||
seriesColors: customColors = null
|
||||
} = params;
|
||||
|
||||
const parsedData = parseData(data);
|
||||
const palette = colorPalettes[theme] || colorPalettes.default;
|
||||
const seriesColorsArr = customColors || parsedData.seriesNames.map((_, i) => palette[i % palette.length]);
|
||||
|
||||
// 背景色和文字色
|
||||
const bgColor = theme === 'dark' ? '#1a1a2e' : '#ffffff';
|
||||
const textColor = theme === 'dark' ? '#e0e0e0' : '#333333';
|
||||
const axisLineColor = theme === 'dark' ? '#444' : '#ddd';
|
||||
|
||||
// 构建系列
|
||||
const series = parsedData.seriesNames.map((name, idx) => {
|
||||
const dataArr = parsedData.seriesData[name];
|
||||
const color = seriesColorsArr[idx] || palette[idx % palette.length];
|
||||
|
||||
let type = chartType === 'bar-line'
|
||||
? (idx % 2 === 0 ? 'bar' : 'line')
|
||||
: chartType;
|
||||
|
||||
const seriesItem = {
|
||||
name: name,
|
||||
type: type,
|
||||
data: [...dataArr],
|
||||
itemStyle: { color: color },
|
||||
emphasis: {
|
||||
focus: 'series',
|
||||
itemStyle: {
|
||||
shadowBlur: 10,
|
||||
shadowColor: 'rgba(0,0,0,0.3)'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (stackMode) {
|
||||
seriesItem.stack = 'total';
|
||||
}
|
||||
|
||||
if (type === 'line') {
|
||||
seriesItem.smooth = smoothLine;
|
||||
seriesItem.lineStyle = { width: 3 };
|
||||
seriesItem.symbolSize = 8;
|
||||
seriesItem.areaStyle = theme === 'gradient' ? { opacity: 0.15 } : undefined;
|
||||
}
|
||||
|
||||
if (type === 'bar') {
|
||||
seriesItem.barMaxWidth = 40;
|
||||
seriesItem.itemStyle.borderRadius = stackMode ? [0, 0, 0, 0] : [4, 4, 0, 0];
|
||||
}
|
||||
|
||||
if (showLabel) {
|
||||
seriesItem.label = {
|
||||
show: true,
|
||||
position: 'top',
|
||||
fontSize: 11,
|
||||
color: textColor,
|
||||
formatter: (p) => {
|
||||
if (p.value >= 10000) return (p.value / 10000).toFixed(1) + 'w';
|
||||
if (p.value >= 1000) return (p.value / 1000).toFixed(1) + 'k';
|
||||
return p.value;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return seriesItem;
|
||||
});
|
||||
|
||||
// 区域分割
|
||||
if (enableSplit && splitIndex < parsedData.categories.length && series.length > 0) {
|
||||
const splitLineColor = theme === 'dark' ? '#ff6b6b' : '#e74c3c';
|
||||
series[0].markArea = {
|
||||
silent: true,
|
||||
data: [
|
||||
[
|
||||
{
|
||||
name: leftLabel,
|
||||
xAxis: parsedData.categories[0],
|
||||
itemStyle: {
|
||||
color: theme === 'dark' ? 'rgba(79,195,247,0.06)' : 'rgba(79,70,229,0.05)',
|
||||
borderWidth: 0
|
||||
},
|
||||
label: {
|
||||
show: true,
|
||||
position: 'insideTop',
|
||||
fontSize: 13,
|
||||
fontWeight: 'bold',
|
||||
color: theme === 'dark' ? '#4fc3f7' : '#4f46e5',
|
||||
offset: [0, 10]
|
||||
}
|
||||
},
|
||||
{ xAxis: parsedData.categories[splitIndex - 1] }
|
||||
],
|
||||
[
|
||||
{
|
||||
name: rightLabel,
|
||||
xAxis: parsedData.categories[splitIndex],
|
||||
itemStyle: {
|
||||
color: theme === 'dark' ? 'rgba(255,107,107,0.06)' : 'rgba(239,68,68,0.05)',
|
||||
borderWidth: 0
|
||||
},
|
||||
label: {
|
||||
show: true,
|
||||
position: 'insideTop',
|
||||
fontSize: 13,
|
||||
fontWeight: 'bold',
|
||||
color: theme === 'dark' ? '#ff6b6b' : '#ef4444',
|
||||
offset: [0, 10]
|
||||
}
|
||||
},
|
||||
{ xAxis: parsedData.categories[parsedData.categories.length - 1] }
|
||||
]
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
// 完整 option
|
||||
const option = {
|
||||
backgroundColor: bgColor,
|
||||
title: title ? {
|
||||
text: title,
|
||||
left: 'center',
|
||||
top: 15,
|
||||
textStyle: {
|
||||
color: textColor,
|
||||
fontSize: 18,
|
||||
fontWeight: 600
|
||||
}
|
||||
} : undefined,
|
||||
tooltip: { show: false },
|
||||
legend: showLegend ? {
|
||||
show: true,
|
||||
top: title ? 50 : 15,
|
||||
textStyle: { color: textColor, fontSize: 12 },
|
||||
itemGap: 20,
|
||||
icon: 'roundRect'
|
||||
} : { show: false },
|
||||
grid: {
|
||||
left: '3%',
|
||||
right: '4%',
|
||||
bottom: '3%',
|
||||
top: showLegend ? (title ? 90 : 60) : (title ? 60 : 30),
|
||||
containLabel: true
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: parsedData.categories,
|
||||
axisLine: { lineStyle: { color: axisLineColor } },
|
||||
axisLabel: {
|
||||
color: textColor,
|
||||
fontSize: 12,
|
||||
interval: 0,
|
||||
rotate: parsedData.categories.length > 10 ? 30 : 0
|
||||
},
|
||||
axisTick: { show: false }
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
axisLine: { show: false },
|
||||
axisTick: { show: false },
|
||||
axisLabel: { color: textColor, fontSize: 11 },
|
||||
splitLine: {
|
||||
show: showGrid,
|
||||
lineStyle: {
|
||||
color: theme === 'dark' ? '#333' : '#f0f0f0',
|
||||
type: 'dashed'
|
||||
}
|
||||
}
|
||||
},
|
||||
series: series,
|
||||
animation: false // 服务端渲染关闭动画
|
||||
};
|
||||
|
||||
return option;
|
||||
}
|
||||
|
||||
// ===== API: 生成图表图片 =====
|
||||
app.post('/api/chart', (req, res) => {
|
||||
try {
|
||||
const params = req.body;
|
||||
|
||||
if (!params.data) {
|
||||
return res.status(400).json({ error: '缺少 data 参数(CSV 格式数据)' });
|
||||
}
|
||||
|
||||
const width = parseInt(params.width) || 800;
|
||||
const height = parseInt(params.height) || 500;
|
||||
const format = params.format || 'png';
|
||||
const pixelRatio = parseInt(params.pixelRatio) || 2;
|
||||
|
||||
// 构建图表配置
|
||||
const option = buildChartOption(params);
|
||||
|
||||
// 创建 canvas 并渲染
|
||||
const canvas = createCanvas(width * pixelRatio, height * pixelRatio);
|
||||
const chart = echarts.init(canvas, null, {
|
||||
renderer: 'canvas',
|
||||
width: width,
|
||||
height: height,
|
||||
devicePixelRatio: pixelRatio
|
||||
});
|
||||
|
||||
chart.setOption(option);
|
||||
|
||||
// 输出图片
|
||||
if (format === 'svg') {
|
||||
// SVG 需要用 SVG 渲染器重新渲染
|
||||
// node-canvas 不支持 SVG,返回 PNG 并提示
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
res.set({
|
||||
'Content-Type': 'image/png',
|
||||
'Content-Length': buffer.length,
|
||||
'X-Chart-Format': 'png',
|
||||
'X-Chart-Note': 'SVG format not supported in server-side rendering, returned PNG instead'
|
||||
});
|
||||
res.send(buffer);
|
||||
} else {
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
res.set({
|
||||
'Content-Type': 'image/png',
|
||||
'Content-Length': buffer.length,
|
||||
'X-Chart-Width': width,
|
||||
'X-Chart-Height': height,
|
||||
'X-Chart-Pixel-Ratio': pixelRatio
|
||||
});
|
||||
res.send(buffer);
|
||||
}
|
||||
|
||||
chart.dispose();
|
||||
} catch (err) {
|
||||
console.error('Chart generation error:', err);
|
||||
res.status(500).json({ error: '图表生成失败: ' + err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// ===== API: 生成图表(GET 方式,方便 URL 直接调用) =====
|
||||
app.get('/api/chart', (req, res) => {
|
||||
try {
|
||||
const params = {
|
||||
data: req.query.data,
|
||||
chartType: req.query.chartType || req.query.type || 'bar',
|
||||
title: req.query.title || '',
|
||||
theme: req.query.theme || 'default',
|
||||
showLegend: req.query.showLegend !== 'false',
|
||||
showGrid: req.query.showGrid !== 'false',
|
||||
showLabel: req.query.showLabel === 'true',
|
||||
stackMode: req.query.stackMode === 'true',
|
||||
smoothLine: req.query.smoothLine !== 'false',
|
||||
enableSplit: req.query.enableSplit === 'true',
|
||||
splitIndex: parseInt(req.query.splitIndex) || 3,
|
||||
leftLabel: req.query.leftLabel || '左侧',
|
||||
rightLabel: req.query.rightLabel || '右侧',
|
||||
splitStyle: req.query.splitStyle || 'solid',
|
||||
width: parseInt(req.query.width) || 800,
|
||||
height: parseInt(req.query.height) || 500,
|
||||
format: req.query.format || 'png',
|
||||
pixelRatio: parseInt(req.query.pixelRatio) || 2
|
||||
};
|
||||
|
||||
if (!params.data) {
|
||||
return res.status(400).json({ error: '缺少 data 参数' });
|
||||
}
|
||||
|
||||
// 解码 data(支持 URL 编码的换行符)
|
||||
params.data = params.data.replace(/\\n/g, '\n');
|
||||
|
||||
const option = buildChartOption(params);
|
||||
|
||||
const width = params.width;
|
||||
const height = params.height;
|
||||
const pixelRatio = params.pixelRatio;
|
||||
|
||||
const canvas = createCanvas(width * pixelRatio, height * pixelRatio);
|
||||
const chart = echarts.init(canvas, null, {
|
||||
renderer: 'canvas',
|
||||
width: width,
|
||||
height: height,
|
||||
devicePixelRatio: pixelRatio
|
||||
});
|
||||
|
||||
chart.setOption(option);
|
||||
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
res.set({
|
||||
'Content-Type': 'image/png',
|
||||
'Content-Length': buffer.length,
|
||||
'X-Chart-Width': width,
|
||||
'X-Chart-Height': height
|
||||
});
|
||||
res.send(buffer);
|
||||
|
||||
chart.dispose();
|
||||
} catch (err) {
|
||||
console.error('Chart generation error:', err);
|
||||
res.status(500).json({ error: '图表生成失败: ' + err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// ===== API: 健康检查 =====
|
||||
app.get('/api/health', (req, res) => {
|
||||
res.json({
|
||||
status: 'ok',
|
||||
service: 'data-chart-tool',
|
||||
version: '1.1.0',
|
||||
endpoints: {
|
||||
'POST /api/chart': '生成图表图片(JSON body)',
|
||||
'GET /api/chart': '生成图表图片(URL 参数)',
|
||||
'GET /api/health': '健康检查'
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ===== API: 文档/使用说明 =====
|
||||
app.get('/api/docs', (req, res) => {
|
||||
res.json({
|
||||
name: '数据可视化图表生成器 API',
|
||||
version: '1.1.0',
|
||||
endpoints: [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/chart',
|
||||
description: '通过 JSON 请求体生成图表图片',
|
||||
'Content-Type': 'application/json',
|
||||
params: {
|
||||
data: { type: 'string', required: true, description: 'CSV 格式数据(第一行表头,第一列横坐标)' },
|
||||
chartType: { type: 'string', default: 'bar', options: ['bar', 'line', 'bar-line'], description: '图表类型' },
|
||||
title: { type: 'string', default: '', description: '图表标题' },
|
||||
theme: { type: 'string', default: 'default', options: ['default', 'dark', 'macarons', 'gradient', 'retro'], description: '主题风格' },
|
||||
showLegend: { type: 'boolean', default: true, description: '是否显示图例' },
|
||||
showGrid: { type: 'boolean', default: true, description: '是否显示网格线' },
|
||||
showLabel: { type: 'boolean', default: false, description: '是否显示数据标签' },
|
||||
stackMode: { type: 'boolean', default: false, description: '是否堆叠模式' },
|
||||
smoothLine: { type: 'boolean', default: true, description: '折线图是否平滑' },
|
||||
enableSplit: { type: 'boolean', default: false, description: '是否启用区域分割' },
|
||||
splitIndex: { type: 'number', default: 3, description: '分割位置索引' },
|
||||
leftLabel: { type: 'string', default: '左侧', description: '左侧区域标签' },
|
||||
rightLabel: { type: 'string', default: '右侧', description: '右侧区域标签' },
|
||||
splitStyle: { type: 'string', default: 'solid', options: ['solid', 'dashed', 'dotted'], description: '分割线样式' },
|
||||
width: { type: 'number', default: 800, description: '图片宽度(px)' },
|
||||
height: { type: 'number', default: 500, description: '图片高度(px)' },
|
||||
format: { type: 'string', default: 'png', options: ['png'], description: '输出格式' },
|
||||
pixelRatio: { type: 'number', default: 2, description: '像素倍率(清晰度)' }
|
||||
},
|
||||
returns: 'image/png',
|
||||
example: {
|
||||
request: `curl -X POST http://localhost:16016/api/chart \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"data": "产品, Q1, Q2, Q3, Q4\\n手机, 1200, 1800, 2100, 2500\\n平板, 800, 950, 1100, 1300",
|
||||
"chartType": "bar",
|
||||
"title": "季度销售对比",
|
||||
"theme": "default",
|
||||
"width": 800,
|
||||
"height": 500
|
||||
}' -o chart.png`,
|
||||
response: 'PNG 图片二进制流'
|
||||
}
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/chart',
|
||||
description: '通过 URL 参数生成图表图片(适合简单场景)',
|
||||
params: {
|
||||
data: { type: 'string', required: true, description: 'CSV 数据(换行用 \\n 分隔)' },
|
||||
type: { type: 'string', default: 'bar', description: '图表类型' },
|
||||
title: { type: 'string', description: '图表标题' },
|
||||
theme: { type: 'string', default: 'default', description: '主题风格' },
|
||||
width: { type: 'number', default: 800 },
|
||||
height: { type: 'number', default: 500 }
|
||||
},
|
||||
returns: 'image/png',
|
||||
example: {
|
||||
request: `curl "http://localhost:16016/api/chart?data=产品,Q1,Q2\\n手机,100,200\\n平板,150,250&type=bar&title=测试" -o chart.png`
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
// ===== 启动服务 =====
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`🚀 数据可视化图表生成器已启动`);
|
||||
console.log(`📊 Web UI: http://0.0.0.0:${PORT}`);
|
||||
console.log(`📡 API: http://0.0.0.0:${PORT}/api/chart`);
|
||||
console.log(`📖 文档: http://0.0.0.0:${PORT}/api/docs`);
|
||||
console.log(`❤️ 健康: http://0.0.0.0:${PORT}/api/health`);
|
||||
});
|
||||
Reference in New Issue
Block a user