Compare commits

..
11 Commits
Author SHA1 Message Date
hz4th_coder 8a5f0b6273 version bump 1.21.0 2026-09-02 14:01:07 +08:00
hz4th_coder 32db3644b8 v1.21.0 x轴标签可读性:新增 xLabelRotate 旋转角度/xLabelInterval 标签间隔/xLabelFontSize 字号 三个图表选项,模型对比图底部横轴字多时可旋转/加间隔避免挤压 2026-09-02 13:59:49 +08:00
hz4th_coder 01c0536986 feat: 数据标签颜色默认同系列+可自定义;Y轴最小/最大值手动指定 v1.20.0
- 数据标签颜色:默认自动取系列颜色(柱状/折线色),也可选自定义颜色手动指定
- Y轴范围:默认自动计算,可手动指定最小/最大值;双Y轴时左/右轴可分别指定
- 主图 + 多图合并 + 服务端API 三处统一;收藏保存/恢复含两项设置
- API 新增参数 labelColorMode/labelColor, yAxisMin/yAxisMax, leftAxisMin/Max, rightAxisMin/Max
2026-08-23 18:15:21 +08:00
hz4th_coder 864c43ab99 feat: 图例上移不遮轴名+按类型显示图标+系列样式细分+轴标题竖直/顶部+X轴名默认取首字段放轴下 v1.19.0
- 双轴图例上移到更靠上位置,轴名在顶部模式时 grid 自动多让位,不再遮住左右轴名
- 图例图标按系列类型自动(柱状=方块、折线=线条),去掉固定 roundRect
- 系列样式细分:柱状实体/空心/阴影,折线实线/虚线/点线(主图+多图合并+服务端API 三处统一)
- 左右轴标题显示方式可选:竖直显示(默认)/轴上部横排,双轴图主图/合并/API 均支持
- X轴名默认自动取数据首列字段名,默认放横坐标轴下方居中;用户手动编辑后不再自动覆盖
- 收藏保存/恢复含系列样式与轴名显示方式
2026-08-23 15:30:36 +08:00
hz4th_coder bc8284d30f feat: 双Y轴图例放到各自轴上方靠两边对齐,不再占用两侧空白区 v1.18.0
- 主图表/多图合并/服务端API 三处统一:左轴图例横排靠左、右轴图例横排靠右,放在各自轴上方
- grid 左右不再为侧边图例让位,绘图区占满整图宽度
- 按实际宽度估算图例换行行数,grid 顶部相应让位避免重叠
2026-08-23 11:06:32 +08:00
hz4th_coder 06cfbca2db chore: 版本号更新至 v1.17.1 2026-08-23 10:09:34 +08:00
hz4th_coder 0e15d43ed4 feat: X轴名右侧不再截字+轴名位置可选(右侧/下方居中)+刻度方向下拉10°档+自定义手动输入 v1.17.1 2026-08-23 10:09:14 +08:00
hz4th_coder 59788639cb chore: 版本号更新至 v1.17.0 2026-08-23 09:51:59 +08:00
hz4th_coder cd7ffab71d docs: README 更新 v1.17.0 功能说明 2026-08-23 09:51:46 +08:00
hz4th_coder 86669f9cf5 feat: X轴轴名+刻度倾斜角度可调(默认水平) + 双Y轴图例按左右轴分组放到对应轴边上 v1.17.0 2026-08-23 09:51:18 +08:00
hz4th_coder 2cc6491440 feat: 数据方向(行=系列)+每系列类型/双轴 + 多图大标题/共享图例 v1.16.0
- 图表模式新增'数据方向':列=系列(默认)/行=系列(第一行是横坐标,每行一个系列),每行可独立设柱状/折线 + 左右轴量度
- 后端 buildChartOption/GET /api/chart 支持 rowsAsSeries + seriesAxis(按系列下标指定左右轴)
- 多图合并每张小图新增:行=系列、双Y轴(左右量度不同)、每系列独立图表类型与坐标轴配置
- 多图合并新增图片大标题(bigTitle),居中显示在顶部
- 多图合并新增图例方式(legendMode):own 各自图例(默认)/shared-top 共用图例顶部/shared-bottom 共用图例底部,共用时各子图隐藏自己的图例、系列合并去重、超宽自动换行
- /api/combine 后端同步支持 bigTitle/legendMode(含深色主题文字适配)
- 收藏功能完整支持新字段(combine 大标题/图例方式/每系列配置,chart 数据方向),编辑恢复正常
- 文档/API.md/README 更新,版本 1.16.0
2026-08-22 12:03:05 +08:00
6 changed files with 1318 additions and 161 deletions
+27 -2
View File
@@ -50,6 +50,8 @@ Content-Type: application/json
| `leftAxisName` | string | — | `""` | 左轴名称(如 `"销售额(元)"` |
| `rightAxisName` | string | — | `""` | 右轴名称(如 `"增长率(%)"` |
| `seriesTypes` | array | — | `null` | 每系列图表类型,按系列顺序对应,如 `["bar","line"]``bar`/`line`/`auto` |
| `seriesAxis` | array | — | `null` | 每系列坐标轴,按系列顺序对应,如 `[0,1]``0`=左轴 `1`=右轴,配合 `dualYAxis`;优先于 `rightAxisSeries` |
| `rowsAsSeries` | boolean | — | `false` | 数据方向:`false`=列=系列(第一列是横坐标,每列一个系列);`true`=行=系列(第一行是横坐标,每行一个系列) |
| `width` | number | — | `800` | 图片宽度(px |
| `height` | number | — | `500` | 图片高度(px |
| `pixelRatio` | number | — | `2` | 像素倍率(越大越清晰) |
@@ -178,10 +180,33 @@ Content-Type: application/json
| `gap` | number | 否 | 图间距(默认 24px |
| `pixelRatio` | number | 否 | 像素倍率,默认 2(越清晰文件越大) |
| `background` | string | 否 | 背景色,默认 `#ffffff` |
| `bigTitle` | string | 否 | 整张图片的大标题(可空),居中显示在顶部 |
| `legendMode` | string | 否 | 图例方式:`own` 每个小图各自图例(默认)/ `shared-top` 共用一套图例放顶部 / `shared-bottom` 共用一套图例放底部(共用时各子图隐藏自己的图例,系列合并去重) |
| `theme` | string | 否 | 大标题/共享图例文字颜色所属主题,默认 `default`(深色用 `dark` |
> 兼容旧参数:`chart1` + `chart2` 仍可传(等价于 `charts: [chart1, chart2]`)。
每个子图配置支持:`data`CSV)、`chartType`bar/line/bar-line/pie/radar)、`title``theme``showLegend``showGrid``showLabel``stackMode``smoothLine``width``height`
每个子图配置支持:`data`CSV)、`chartType`bar/line/bar-line/pie/radar)、`title``theme``showLegend``showGrid``showLabel``stackMode``smoothLine``width``height`,以及**数据方向与多类型双轴**`rowsAsSeries`(行=系列)、`dualYAxis``leftAxisName``rightAxisName``seriesTypes``seriesAxis`
### 高级示例(大标题 + 底部共享图例 + 行=系列 + 柱状/折线双轴)
```bash
curl -X POST http://127.0.0.1:16016/api/combine \
-H "Content-Type: application/json" \
-d '{
"bigTitle": "经营总览大图",
"legendMode": "shared-bottom",
"direction": "grid",
"cols": 2,
"charts": [
{"data": "指标, 2023, 2024, 2025\n营收(元), 1200, 1800, 2100\n销量(个), 100, 150, 130",
"rowsAsSeries": true, "chartType": "bar", "title": "营收与销量",
"dualYAxis": true, "leftAxisName": "元", "rightAxisName": "个",
"seriesTypes": ["bar","line"], "seriesAxis": [0,1]},
{"data": "产品, Q1, Q2\n手机, 1200, 1800\n平板, 800, 950", "chartType": "bar", "title": "季度销售"}
]
}' -o combine.png
```
### curl 示例
@@ -248,7 +273,7 @@ curl http://192.168.0.101:16016/api/health
{
"status": "ok",
"service": "data-chart-tool",
"version": "1.1.0",
"version": "1.16.0",
"endpoints": {
"POST /api/chart": "生成图表图片(JSON body",
"GET /api/chart": "生成图表图片(URL 参数)",
+12 -5
View File
@@ -3,7 +3,7 @@
一个简洁强大的数据可视化工具,支持 **Web UI****API** 两种方式生成精美的对比图表和表格图片。
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Version](https://img.shields.io/badge/version-1.8.0-green.svg)
![Version](https://img.shields.io/badge/version-1.20.0-green.svg)
## ✨ 功能特性
@@ -13,7 +13,12 @@
- **混合图** - 柱状图+折线图组合展示
- **饼图** - 环形占比展示(第一列=名称,第一系列=数值)
- **雷达图** - 多维度对比(第一列=维度,每个系列=一个多边形)
- **双Y轴** - 一张图左右两个坐标轴,量度可不同,左右轴可独立命名,系列可指定左轴/右轴且每种类型独立设置(柱状/折线)
- **双Y轴** - 一张图左右两个坐标轴,量度可不同,左右轴可独立命名,系列可指定左轴/右轴且每种类型独立设置(柱状/折线);开启双轴时**图例放在各自轴上方、各自往两边对齐**(左轴系列图例靠左、右轴系列图例靠右,附「左轴/右轴」分组标题),不再占用两侧空白区,绘图区占满整图宽度;**图例图标随系列类型自动变化**(柱状=方块、折线=线条);**左右轴标题显示方式可选**(竖直显示/轴上部横排)
- **系列样式细分** - 每个系列可单独设置图表类型与样式:**柱状**分实体/空心/阴影,**折线**分实线/虚线/点线,图例与样式联动
- **数据标签颜色** - 显示数据标签时颜色**默认同系列颜色**(柱状/折线色),也可手动指定自定义颜色
- **Y轴范围** - 默认自动计算,也可**手动指定 Y 轴最小/最大值**;双Y轴时左轴、右轴可分别指定范围
- **X轴设置** - 横坐标轴名**默认自动取数据首列字段名**,**默认放在横坐标轴下方居中**(也可选右侧末端);选轴名时自动预留空间不再截字;刻度文字方向**默认水平(0°)**,支持**下拉档位(每10°)** + **手动输入任意度数(0-90°)**,解决长类别名重叠问题
- **数据方向(行=系列)** - 支持"行=系列"布局:第一行是横坐标,每行一个系列,每行可独立设置图表类型(柱状/折线)与左右轴量度(如:营收行=柱状左轴,销量行=折线右轴)
### 📋 表格功能
- **表格图片生成** - 根据数据生成精美的表格图片
@@ -35,15 +40,17 @@
### 🖼️ 多图合并
- 将多张图表合并到一张图片中,适合对比/汇总场景,**默认2张,可一键不断添加**(支持删除)
- 支持**横排(单行)**、**竖排(单列)**、**多行多列网格**(可设每行列数),一键切换实时预览
- 每张图可独立配置:数据、标题、图表类型、主题、图例/网格/标签/堆叠
- 每张图可独立配置:数据、标题、图表类型、主题、图例/网格/标签/堆叠,以及**数据方向(行=系列)**、**双Y轴(不同左右量度)**、**X轴设置(轴名+刻度倾斜角)**、**每系列独立图表类型与坐标轴**
- **图片大标题** - 可编写整张大图的标题,居中显示在顶部(可留空)
- **共用图例** - 图例方式可选:每个小图各自图例 / 共用一套图例放顶部 / 共用一套图例放底部;共用时所有小图的系列合并去重,同名系列只显示一次,各小图隐藏自己的图例
- 支持导出 PNG
### 📡 API 接口
- **POST /api/chart** - JSON 请求体生成图表(完整参数支持)
- **POST /api/chart** - JSON 请求体生成图表(完整参数支持,含 rowsAsSeries/seriesTypes/seriesAxis/dualYAxis
- **GET /api/chart** - URL 参数生成图表(简单场景)
- **POST /api/table** - JSON 请求体生成表格图片
- **GET /api/table** - URL 参数生成表格图片
- **POST /api/combine** - 多图合并(横排/竖排)生成一张图片
- **POST /api/combine** - 多图合并(横排/竖排/网格)生成一张图片,支持 bigTitle(大标题)与 legendModeown/shared-top/shared-bottom 共享图例)
- 返回 PNG 图片,支持自定义分辨率和像素倍率
### 📥 导出功能
+794 -82
View File
File diff suppressed because it is too large Load Diff
+105 -1
View File
@@ -66,11 +66,55 @@ C, 20, 30, 40</pre>
</select>
</div>
<div class="config-group">
<label>数据方向</label>
<select id="dataOrientation" onchange="onDataOrientationChange()">
<option value="columns">列=系列(第一列是横坐标,每列一个系列)</option>
<option value="rows">行=系列(第一行是横坐标,每行一个系列)</option>
</select>
<p class="hint-text">「行=系列」示例:<br>指标, 2023, 2024, 2025<br>营收(元), 1200, 1800, 2100<br>销量(个), 100, 150, 130<br>—— 每行可单独设柱状/折线 + 左右轴</p>
</div>
<div class="config-group">
<label>标题</label>
<input type="text" id="chartTitle" placeholder="图表标题" oninput="updateChart()">
</div>
<div class="config-group">
<label>X轴设置</label>
<div class="config-group">
<label>横坐标轴名(留空时自动用数据首列字段名)</label>
<input type="text" id="xAxisName" placeholder="默认取数据首列字段名,如:月份" oninput="onXAxisNameInput()">
</div>
<div class="config-group">
<label>轴名位置</label>
<select id="xAxisNameLoc" onchange="updateChart()">
<option value="middle" selected>横坐标轴下方居中</option>
<option value="end">横坐标右侧末端</option>
</select>
</div>
<div class="config-group">
<label>刻度文字方向(0°=水平 · 倾斜可防长名重叠)</label>
<div class="res-input-row">
<select id="xLabelRotate" onchange="onXLabelRotateChange()" style="flex:1">
<option value="0">0° 水平</option>
<option value="10">10°</option>
<option value="20">20°</option>
<option value="30">30°</option>
<option value="40">40°</option>
<option value="50">50°</option>
<option value="60">60°</option>
<option value="70">70°</option>
<option value="80">80°</option>
<option value="90">90° 竖直</option>
<option value="custom">自定义…</option>
</select>
<input type="number" id="xLabelRotateCustom" min="0" max="90" value="0" style="width:70px;display:none" title="手动输入0-90°" oninput="onXLabelRotateCustomInput()">
<span class="res-times">°</span>
</div>
</div>
</div>
<div class="config-group">
<label>主题风格</label>
<select id="themeStyle" onchange="syncThemeButtons(this.value); updateChart()">
@@ -111,6 +155,40 @@ C, 20, 30, 40</pre>
</div>
</div>
<div class="config-group" id="labelColorGroup" style="display:none;">
<label>数据标签颜色(默认同系列颜色)</label>
<div class="res-input-row">
<select id="labelColorMode" onchange="onLabelColorModeChange()" style="flex:1">
<option value="auto" selected>自动(同系列颜色)</option>
<option value="custom">自定义…</option>
</select>
<input type="color" id="labelColor" value="#333333" style="width:44px;height:32px;display:none" onchange="updateChart()">
</div>
</div>
<div class="config-group">
<label>Y轴范围(留空=自动)</label>
<div id="singleAxisRange">
<div class="res-input-row">
<input type="number" id="yAxisMin" placeholder="最小值" oninput="updateChart()">
<span class="res-times">~</span>
<input type="number" id="yAxisMax" placeholder="最大值" oninput="updateChart()">
</div>
</div>
<div id="dualAxisRange" style="display:none;">
<div class="res-input-row">
<input type="number" id="leftAxisMin" placeholder="左轴最小" oninput="updateChart()">
<span class="res-times">~</span>
<input type="number" id="leftAxisMax" placeholder="左轴最大" oninput="updateChart()">
</div>
<div class="res-input-row" style="margin-top:8px">
<input type="number" id="rightAxisMin" placeholder="右轴最小" oninput="updateChart()">
<span class="res-times">~</span>
<input type="number" id="rightAxisMax" placeholder="右轴最大" oninput="updateChart()">
</div>
</div>
</div>
<div class="config-group" id="rightAxisGroup" style="display:none;">
<label>左右轴名称(量度可不同)</label>
<div class="res-input-row">
@@ -118,7 +196,18 @@ C, 20, 30, 40</pre>
<span class="res-times">/</span>
<input type="text" id="rightAxisName" placeholder="右轴,如:增长率(%)" oninput="updateChart()">
</div>
<p class="hint-text">在下方「系列配置」中可指定每个系列用左轴/右轴及图表类型(柱状/折线)</p>
<div class="res-input-row" style="margin-top:8px">
<select id="leftAxisNameLoc" onchange="updateChart()" title="左轴标题显示方式">
<option value="vertical" selected>左轴标题 · 竖直显示</option>
<option value="top">左轴标题 · 轴上部</option>
</select>
<span class="res-times">/</span>
<select id="rightAxisNameLoc" onchange="updateChart()" title="右轴标题显示方式">
<option value="vertical" selected>右轴标题 · 竖直显示</option>
<option value="top">右轴标题 · 轴上部</option>
</select>
</div>
<p class="hint-text">在下方「系列配置」中可指定每个系列用左轴/右轴、图表类型(柱状/折线)及样式(实体/空心/阴影、实线/虚线/点线)</p>
</div>
</div>
@@ -284,6 +373,21 @@ C, 20, 30, 40</pre>
<div class="panel-section" id="combineConfigSection" style="display:none;">
<h2>🖼️ 多图合并配置</h2>
<div class="config-group">
<label>图片大标题(可选)</label>
<input type="text" id="combineBigTitle" placeholder="整张大图的大标题,留空则不显示" oninput="generateCombine()">
</div>
<div class="config-group">
<label>图例方式</label>
<select id="combineLegendMode" onchange="generateCombine()">
<option value="own">每个小图各自图例</option>
<option value="shared-top">共用一套图例(顶部)</option>
<option value="shared-bottom">共用一套图例(底部)</option>
</select>
<p class="hint-text">共用图例时:所有小图的系列合并去重,放在整张图片顶部/底部,各小图隐藏自己的图例;同名系列只显示一次</p>
</div>
<div class="config-group">
<label>排列方式</label>
<div class="combine-direction">
+344 -71
View File
@@ -45,8 +45,8 @@ const colorPalettes = {
mint: ['#00bfa5', '#26a69a', '#4db6ac', '#80cbc4', '#b2dfdb', '#00897b', '#00796b', '#004d40', '#009688']
};
// ===== 数据解析(与前端一致 =====
function parseData(rawText) {
// ===== 数据解析(rowsAsSeries=true 时“行=系列”:第一行是横坐标,每行一个系列 =====
function parseData(rawText, rowsAsSeries) {
const lines = rawText.trim().split('\n').filter(l => l.trim());
if (lines.length < 2) {
throw new Error('数据至少需要包含表头和一行数据');
@@ -68,6 +68,32 @@ function parseData(rawText) {
const categories = [];
const seriesData = {};
if (rowsAsSeries) {
// 行=系列:第一列=系列名,表头除第一列外=横坐标
const names = [];
const nameSet = {};
rows.slice(1).forEach(r => {
const n = ((r && r[0]) || '').trim();
if (n && !nameSet[n]) { nameSet[n] = true; names.push(n); }
});
names.forEach(n => { seriesData[n] = []; });
for (let j = 1; j < headers.length; j++) {
categories.push(headers[j]);
for (let i = 1; i < rows.length; i++) {
const r = rows[i];
const name = ((r && r[0]) || '').trim();
if (!seriesData[name]) continue;
const val = parseFloat(r[j]);
seriesData[name].push(isNaN(val) ? 0 : val);
}
}
return {
categories,
seriesNames: names,
seriesData
};
}
for (let i = 1; i < headers.length; i++) {
seriesData[headers[i]] = [];
}
@@ -98,6 +124,41 @@ function adjustColor(hex, amount) {
}
// ===== 构建 ECharts option =====
function hexToRgba(hex, alpha) {
hex = String(hex || '#888').replace('#', '');
if (hex.length === 3) hex = hex.split('').map(c => c + c).join('');
const num = parseInt(hex, 16);
return `rgba(${(num >> 16) & 255},${(num >> 8) & 255},${num & 255},${alpha})`;
}
// 系列细分样式:柱状(实体/空心/阴影),折线(实线/虚线/点线)
function applySeriesStyle(seriesItem, type, color, style) {
if (!style || style === 'solid') return;
if (type === 'bar') {
if (style === 'hollow') {
const fill = (typeof color === 'string' && color.charAt(0) === '#') ? hexToRgba(color, 0.12) : 'rgba(120,120,120,0.12)';
seriesItem.itemStyle.color = fill;
seriesItem.itemStyle.borderColor = (typeof color === 'string' && color.charAt(0) === '#') ? color : '#888';
seriesItem.itemStyle.borderWidth = 2;
} else if (style === 'shadow') {
seriesItem.itemStyle.shadowBlur = 14;
seriesItem.itemStyle.shadowColor = (typeof color === 'string' && color.charAt(0) === '#') ? hexToRgba(color, 0.55) : 'rgba(0,0,0,0.35)';
seriesItem.itemStyle.shadowOffsetY = 4;
}
} else if (type === 'line') {
if (!seriesItem.lineStyle) seriesItem.lineStyle = { width: 3 };
if (style === 'dashed') seriesItem.lineStyle.type = 'dashed';
else if (style === 'dotted') seriesItem.lineStyle.type = 'dotted';
}
}
// Y轴 min/max:空值/非法返回 undefinedECharts 自动)
function axisNum(v) {
if (v === '' || v === undefined || v === null) return undefined;
const n = parseFloat(v);
return isNaN(n) ? undefined : n;
}
function buildChartOption(params) {
const {
data,
@@ -119,10 +180,26 @@ function buildChartOption(params) {
rightAxisSeries = null,
leftAxisName = '',
rightAxisName = '',
seriesTypes = null
seriesTypes = null,
seriesAxis = null,
seriesStyles = null,
leftAxisNameLoc = 'vertical',
rightAxisNameLoc = 'vertical',
labelColorMode = 'auto',
labelColor = '#333333',
yAxisMin = '',
yAxisMax = '',
leftAxisMin = '',
leftAxisMax = '',
rightAxisMin = '',
rightAxisMax = '',
xLabelRotate = '',
xLabelInterval = '',
xLabelFontSize = 0,
width = 800
} = params;
const parsedData = parseData(data);
const parsedData = parseData(data, params.rowsAsSeries);
const palette = colorPalettes[theme] || colorPalettes.default;
const seriesColorsArr = customColors || parsedData.seriesNames.map((_, i) => palette[i % palette.length]);
@@ -225,10 +302,16 @@ function buildChartOption(params) {
}
};
// 双Y轴:rightAxisSeries 指定右轴系列名
// 双Y轴:rightAxisSeries 按名称指定右轴seriesAxis 按系列下标(0左 1右)
if (dualYAxis) {
const rightNames = Array.isArray(rightAxisSeries) ? rightAxisSeries : (rightAxisSeries ? [rightAxisSeries] : []);
seriesItem.yAxisIndex = rightNames.includes(name) ? 1 : 0;
let axisIdx = 0;
if (Array.isArray(seriesAxis) && seriesAxis[idx] !== undefined && seriesAxis[idx] !== null && seriesAxis[idx] !== '') {
axisIdx = Number(seriesAxis[idx]) === 1 ? 1 : 0;
} else {
const rightNames = Array.isArray(rightAxisSeries) ? rightAxisSeries : (rightAxisSeries ? [rightAxisSeries] : []);
axisIdx = rightNames.includes(name) ? 1 : 0;
}
seriesItem.yAxisIndex = axisIdx;
}
if (stackMode) {
@@ -246,12 +329,17 @@ function buildChartOption(params) {
seriesItem.itemStyle.borderRadius = stackMode ? [0, 0, 0, 0] : [4, 4, 0, 0];
}
// 系列细分样式:柱状(实体/空心/阴影) / 折线(实线/虚线/点线)
const st = Array.isArray(seriesStyles) ? seriesStyles[idx] : null;
applySeriesStyle(seriesItem, type, color, st);
// 数据标签:颜色默认同系列颜色,可手动自定义
if (showLabel) {
seriesItem.label = {
show: true,
position: 'top',
fontSize: 11,
color: textColor,
color: labelColorMode === 'custom' ? labelColor : color,
formatter: (p) => {
if (p.value >= 10000) return (p.value / 10000).toFixed(1) + 'w';
if (p.value >= 1000) return (p.value / 1000).toFixed(1) + 'k';
@@ -311,6 +399,58 @@ function buildChartOption(params) {
};
}
// 双Y轴:图例放到各自轴上方(左图例靠左、右图例靠右),不再占用两侧空白;图标按系列类型自动
let legendOpt, gridTop;
if (dualYAxis && showLegend) {
const left = [], right = [];
series.forEach(s => { if (s.yAxisIndex === 1) right.push(s.name); else left.push(s.name); });
const legendTop = title ? 42 : 8;
const availW = Math.max(100, (width - 20) / 2);
// 粗略估算文字宽度:中文≈字号宽,ASCII≈字号*0.6
const textW = (n) => [...String(n)].reduce((w, ch) => w + (ch.charCodeAt(0) > 255 ? 12 : 7), 0);
const estRows = (names) => {
if (!names || !names.length) return 0;
const icon = 14, sw = 6, ig = 14;
let cur = 0, rows = 1;
names.forEach(n => {
const itemW = icon + sw + textW(n);
if (cur && cur + ig + itemW > availW) { rows++; cur = itemW; }
else cur += itemW + (cur ? ig : 0);
});
return rows;
};
const rows = Math.max(estRows(left), estRows(right));
const legendH = rows * 22 + 6;
const needNameTopGap = (leftAxisNameLoc === 'top' || rightAxisNameLoc === 'top');
legendOpt = [
{
show: left.length > 0,
orient: 'horizontal', left: 8,
top: legendTop, width: '49%',
data: left,
title: left.length > 1 ? { text: '左轴', textStyle: { color: textColor, fontSize: 11, fontWeight: 600 } } : undefined,
textStyle: { color: textColor, fontSize: 12 }, itemGap: 14
},
{
show: right.length > 0,
orient: 'horizontal', right: 8,
top: legendTop, width: '49%',
data: right,
title: right.length > 1 ? { text: '右轴', textStyle: { color: textColor, fontSize: 11, fontWeight: 600 } } : undefined,
textStyle: { color: textColor, fontSize: 12 }, itemGap: 14
}
];
gridTop = legendTop + legendH + (needNameTopGap ? 24 : 8);
} else {
legendOpt = showLegend ? {
show: true,
top: title ? 44 : 10,
textStyle: { color: textColor, fontSize: 12 },
itemGap: 20
} : { show: false };
gridTop = showLegend ? (title ? 90 : 60) : (title ? 60 : 30);
}
// 完整 option
const option = {
backgroundColor: bgColor,
@@ -325,18 +465,12 @@ function buildChartOption(params) {
}
} : undefined,
tooltip: { show: false },
legend: showLegend ? {
show: true,
top: title ? 50 : 15,
textStyle: { color: textColor, fontSize: 12 },
itemGap: 20,
icon: 'roundRect'
} : { show: false },
legend: legendOpt,
grid: {
left: '3%',
right: '4%',
bottom: '3%',
top: showLegend ? (title ? 90 : 60) : (title ? 60 : 30),
top: gridTop,
containLabel: true
},
xAxis: {
@@ -345,9 +479,11 @@ function buildChartOption(params) {
axisLine: { lineStyle: { color: axisLineColor } },
axisLabel: {
color: textColor,
fontSize: 12,
interval: 0,
rotate: parsedData.categories.length > 10 ? 30 : 0
fontSize: xLabelFontSize > 0 ? xLabelFontSize : 12,
interval: xLabelInterval === '' ? 0 : Number(xLabelInterval),
rotate: xLabelRotate === ''
? (parsedData.categories.length > 10 ? 30 : 0)
: Number(xLabelRotate)
},
axisTick: { show: false }
},
@@ -355,7 +491,12 @@ function buildChartOption(params) {
{
type: 'value',
name: leftAxisName || '左轴',
nameTextStyle: { color: textColor, fontSize: 11, padding: [0, 0, 0, 4] },
min: axisNum(leftAxisMin),
max: axisNum(leftAxisMax),
nameLocation: leftAxisNameLoc === 'top' ? 'end' : 'middle',
nameRotate: leftAxisNameLoc === 'top' ? 0 : 90,
nameGap: leftAxisNameLoc === 'top' ? 12 : 32,
nameTextStyle: { color: textColor, fontSize: 11 },
axisLine: { show: false },
axisTick: { show: false },
axisLabel: { color: textColor, fontSize: 11 },
@@ -371,7 +512,12 @@ function buildChartOption(params) {
type: 'value',
name: rightAxisName || '右轴',
position: 'right',
nameTextStyle: { color: textColor, fontSize: 11, padding: [0, 4, 0, 0] },
min: axisNum(rightAxisMin),
max: axisNum(rightAxisMax),
nameLocation: rightAxisNameLoc === 'top' ? 'end' : 'middle',
nameRotate: rightAxisNameLoc === 'top' ? 0 : 90,
nameGap: rightAxisNameLoc === 'top' ? 12 : 32,
nameTextStyle: { color: textColor, fontSize: 11 },
axisLine: { show: false },
axisTick: { show: false },
axisLabel: { color: textColor, fontSize: 11 },
@@ -379,6 +525,8 @@ function buildChartOption(params) {
}
] : {
type: 'value',
min: axisNum(yAxisMin),
max: axisNum(yAxisMax),
axisLine: { show: false },
axisTick: { show: false },
axisLabel: { color: textColor, fontSize: 11 },
@@ -479,6 +627,19 @@ app.get('/api/chart', (req, res) => {
leftAxisName: req.query.leftAxisName || '',
rightAxisName: req.query.rightAxisName || '',
seriesTypes: req.query.seriesTypes ? req.query.seriesTypes.split(',') : null,
seriesAxis: req.query.seriesAxis ? req.query.seriesAxis.split(',').map(Number) : null,
seriesStyles: req.query.seriesStyles ? req.query.seriesStyles.split(',') : null,
leftAxisNameLoc: req.query.leftAxisNameLoc || 'vertical',
rightAxisNameLoc: req.query.rightAxisNameLoc || 'vertical',
labelColorMode: req.query.labelColorMode || 'auto',
labelColor: req.query.labelColor || '#333333',
yAxisMin: req.query.yAxisMin || '',
yAxisMax: req.query.yAxisMax || '',
leftAxisMin: req.query.leftAxisMin || '',
leftAxisMax: req.query.leftAxisMax || '',
rightAxisMin: req.query.rightAxisMin || '',
rightAxisMax: req.query.rightAxisMax || '',
rowsAsSeries: req.query.rowsAsSeries === 'true',
width: parseInt(req.query.width) || 800,
height: parseInt(req.query.height) || 500,
format: req.query.format || 'png',
@@ -995,7 +1156,7 @@ app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
service: 'data-chart-tool',
version: '1.15.0',
version: '1.21.0',
endpoints: {
'POST /api/chart': '生成图表图片(JSON body',
'GET /api/chart': '生成图表图片(URL 参数)',
@@ -1015,7 +1176,7 @@ app.get('/api/health', (req, res) => {
app.get('/api/docs', (req, res) => {
res.json({
name: '数据可视化图表生成器 API',
version: '1.15.0',
version: '1.21.0',
endpoints: [
{
method: 'POST',
@@ -1045,7 +1206,20 @@ app.get('/api/docs', (req, res) => {
rightAxisSeries: { type: 'array', default: null, description: '右轴系列名列表(如 ["利润"],指定哪些系列用右轴)' },
leftAxisName: { type: 'string', default: '', description: '左轴名称' },
rightAxisName: { type: 'string', default: '', description: '右轴名称' },
seriesTypes: { type: 'array', default: null, description: '每系列图表类型(如 ["bar","line"],按系列顺序对应,bar/line/auto' }
seriesTypes: { type: 'array', default: null, description: '每系列图表类型(如 ["bar","line"],按系列顺序对应,bar/line/auto' },
seriesAxis: { type: 'array', default: null, description: '每系列坐标轴(如 [0,1]0=左轴 1=右轴,配合 dualYAxis 使用;优先于 rightAxisSeries' },
seriesStyles: { type: 'array', default: null, description: '每系列样式(如 ["solid","dashed"],柱状支持 solid实体/hollow空心/shadow阴影,折线支持 solid实线/dashed虚线/dotted点线)' },
leftAxisNameLoc: { type: 'string', default: 'vertical', options: ['vertical', 'top'], description: '左轴标题显示方式:vertical=竖直显示(默认)top=轴上部横排' },
rightAxisNameLoc: { type: 'string', default: 'vertical', options: ['vertical', 'top'], description: '右轴标题显示方式:vertical=竖直显示(默认)top=轴上部横排' },
labelColorMode: { type: 'string', default: 'auto', options: ['auto', 'custom'], description: '数据标签颜色:auto=同系列颜色(默认)custom=手动指定 labelColor' },
labelColor: { type: 'string', default: '#333333', description: '数据标签自定义颜色(labelColorMode=custom 时生效)' },
yAxisMin: { type: 'string', default: '', description: '单Y轴最小值(留空=自动)' },
yAxisMax: { type: 'string', default: '', description: '单Y轴最大值(留空=自动)' },
leftAxisMin: { type: 'string', default: '', description: '双Y轴左轴最小值(留空=自动)' },
leftAxisMax: { type: 'string', default: '', description: '双Y轴左轴最大值(留空=自动)' },
rightAxisMin: { type: 'string', default: '', description: '双Y轴右轴最小值(留空=自动)' },
rightAxisMax: { type: 'string', default: '', description: '双Y轴右轴最大值(留空=自动)' },
rowsAsSeries: { type: 'boolean', default: false, description: '数据方向:false=列=系列(第一列是横坐标,每列一个系列);true=行=系列(第一行是横坐标,每行一个系列)' }
},
returns: 'image/png',
example: {
@@ -1127,15 +1301,18 @@ app.get('/api/docs', (req, res) => {
{
method: 'POST',
path: '/api/combine',
description: '将多张图表合并到一张图片中(支持横排/竖排)',
description: '将多张图表合并到一张图片中(支持横排/竖排/网格,支持整图大标题与共享图例',
'Content-Type': 'application/json',
params: {
charts: { type: 'array', required: true, description: '图表配置数组(N 张),每项同 /api/chart 参数;兼容 chart1 + chart2' },
charts: { type: 'array', required: true, description: '图表配置数组(N 张),每项同 /api/chart 参数(含 seriesTypes/seriesAxis/dualYAxis 等);兼容 chart1 + chart2' },
direction: { type: 'string', default: 'horizontal', options: ['horizontal', 'vertical', 'grid'], description: '排布方式:horizontal 横排(单行)/ vertical 竖排(单列)/ grid 多行多列' },
cols: { type: 'number', default: 2, description: '多行多列时的每行列数(仅 grid 生效)' },
gap: { type: 'number', default: 24, description: '图间距(px)' },
pixelRatio: { type: 'number', default: 2, description: '像素倍率(清晰度)' },
background: { type: 'string', default: '#ffffff', description: '背景色' }
background: { type: 'string', default: '#ffffff', description: '背景色' },
bigTitle: { type: 'string', default: '', description: '整张图片的大标题(可空)' },
legendMode: { type: 'string', default: 'own', options: ['own', 'shared-top', 'shared-bottom'], description: '图例方式:own 每个小图各自图例 / shared-top 共用图例放顶部 / shared-bottom 共用图例放底部(共用时各子图隐藏自己的图例)' },
theme: { type: 'string', default: 'default', description: '大标题/共享图例文字颜色所属主题(深色用 dark)' }
},
returns: 'image/png',
example: {
@@ -1187,6 +1364,27 @@ app.get('/api/docs', (req, res) => {
});
});
// ===== 多图合并:收集共享图例条目(按名称去重) =====
function combineLegendItems(charts) {
const items = [];
const seen = {};
charts.forEach(c => {
if (!c || !c.data) return;
let p;
try { p = parseData(c.data, c.rowsAsSeries); } catch (e) { return; }
if (!p || !p.seriesNames) return;
const palette = colorPalettes[c.theme] || colorPalettes.default;
const custom = Array.isArray(c.seriesColors) ? c.seriesColors : null;
p.seriesNames.forEach((name, idx) => {
if (!seen[name]) {
seen[name] = true;
items.push({ name, color: custom ? (custom[idx] || palette[idx % palette.length]) : palette[idx % palette.length] });
}
});
});
return items;
}
// ===== API: 多图合并生成图片 =====
app.post('/api/combine', async (req, res) => {
try {
@@ -1210,11 +1408,19 @@ app.post('/api/combine', async (req, res) => {
const gap = parseInt(body.gap) || 24;
const pixelRatio = parseInt(body.pixelRatio) || 2;
const background = body.background || '#ffffff';
const bigTitle = String(body.bigTitle || '');
const legendMode = ['shared-top', 'shared-bottom'].includes(body.legendMode) ? body.legendMode : 'own';
const sharedLegend = legendMode !== 'own';
const theme = body.theme || 'default';
const textColor = theme === 'dark' ? '#e0e0e0' : '#333333';
// 渲染单个子图(直接按目标尺寸渲染,避免二次缩放损失)
// 渲染单个子图(共享图例时隐藏各子图自己的图例;直接按目标尺寸渲染,避免二次缩放损失)
// 注意:必须先 toBuffer 再 chart.dispose()dispose 会清空 canvas 内容!
const renderSub = async (params, w, h) => {
const option = buildChartOption(params);
const p = { ...params };
if (sharedLegend) p.showLegend = false;
p.width = w; // 双轴顶部图例换行估算用实际子图宽度
const option = buildChartOption(p);
const c = createCanvas(w * pixelRatio, h * pixelRatio);
const chart = echarts.init(c, null, {
renderer: 'canvas',
@@ -1233,10 +1439,8 @@ app.post('/api/combine', async (req, res) => {
renderSub(c, parseInt(c.width) || 640, parseInt(c.height) || 420)
));
let W, H;
const canvas = createCanvas(1, 1);
const ctx = canvas.getContext('2d');
// 基础布局(不含大标题/共享图例):计算子图单元格位置
let W, H, cells = [];
if (direction === 'grid') {
// 多行多列网格:所有子图统一 contain 到最大单元格,按列填充
const rows = Math.ceil(subs.length / cols);
@@ -1244,53 +1448,122 @@ app.post('/api/combine', async (req, res) => {
const cellH = Math.max(...subs.map(s => s.h));
W = cols * cellW + (cols - 1) * gap;
H = rows * cellH + (rows - 1) * gap;
canvas.width = W * pixelRatio;
canvas.height = H * pixelRatio;
ctx.fillStyle = background;
ctx.fillRect(0, 0, W * pixelRatio, H * pixelRatio);
subs.forEach((s, i) => {
const r = Math.floor(i / cols), c = i % cols;
const scale = Math.min(cellW / s.w, cellH / s.h);
const dw = Math.round(s.w * scale), dh = Math.round(s.h * scale);
const x = c * (cellW + gap) + Math.round((cellW - dw) / 2);
const y = r * (cellH + gap) + Math.round((cellH - dh) / 2);
ctx.drawImage(s.img, x * pixelRatio, y * pixelRatio, dw * pixelRatio, dh * pixelRatio);
cells.push({
img: s.img,
x: c * (cellW + gap) + Math.round((cellW - dw) / 2),
y: r * (cellH + gap) + Math.round((cellH - dh) / 2),
w: dw, h: dh
});
});
} else if (direction === 'vertical') {
// 竖排(上下):等宽对齐
const tw = Math.max(...subs.map(s => s.w));
let y = 0;
cells = subs.map(s => {
const h = Math.round(s.h * (tw / s.w));
const cell = { img: s.img, x: 0, y, w: tw, h };
y += h + gap;
return cell;
});
W = tw;
H = y - gap;
} else {
let scaled;
if (direction === 'vertical') {
// 竖排(上下):等宽对齐
const tw = Math.max(...subs.map(s => s.w));
scaled = subs.map(s => ({ img: s.img, w: tw, h: Math.round(s.h * (tw / s.w)) }));
W = tw;
H = scaled.reduce((sum, s) => sum + s.h, 0) + gap * (scaled.length - 1);
} else {
// 横排(左右):等高对齐
const th = Math.max(...subs.map(s => s.h));
scaled = subs.map(s => ({ img: s.img, w: Math.round(s.w * (th / s.h)), h: th }));
W = scaled.reduce((sum, s) => sum + s.w, 0) + gap * (scaled.length - 1);
H = th;
}
// 横排(左右):等高对齐
const th = Math.max(...subs.map(s => s.h));
let x = 0;
cells = subs.map(s => {
const w = Math.round(s.w * (th / s.h));
const cell = { img: s.img, x, y: 0, w, h: th };
x += w + gap;
return cell;
});
W = x - gap;
H = th;
}
canvas.width = W * pixelRatio;
canvas.height = H * pixelRatio;
ctx.fillStyle = background;
ctx.fillRect(0, 0, W * pixelRatio, H * pixelRatio);
// 共享图例:按宽度换行计算
const legendFont = 13, swatch = 14, sw = 5, ig = 18, lineH = legendFont + 10;
let legendRows = [], legendH = 0;
if (sharedLegend) {
const items = combineLegendItems(charts);
const tmp = createCanvas(10, 10);
const tctx = tmp.getContext('2d');
tctx.font = `${legendFont}px "Noto Sans CJK SC", sans-serif`;
const maxW = W - 20;
let cur = [], curW = 0;
items.forEach(it => {
const itemW = swatch + sw + tctx.measureText(it.name).width;
if (cur.length && curW + ig + itemW > maxW) { legendRows.push(cur); cur = []; curW = 0; }
cur.push(it);
curW += itemW + (cur.length > 1 ? ig : 0);
});
if (cur.length) legendRows.push(cur);
legendH = legendRows.length * lineH + 8;
}
if (direction === 'vertical') {
// 5 参数形式:drawImage(img, dx, dy, dw, dh),源整图缩放到目标矩形
let y = 0;
scaled.forEach(s => {
ctx.drawImage(s.img, 0, y * pixelRatio, s.w * pixelRatio, s.h * pixelRatio);
y += s.h + gap;
// 大标题区高度
const titleFont = 34;
const titleH = bigTitle ? titleFont + 26 : 0;
const topOffset = titleH + (legendMode === 'shared-top' ? legendH + 12 : 0);
const bottomOffset = legendMode === 'shared-bottom' ? legendH + 12 : 0;
const totalH = H + topOffset + bottomOffset;
// 创建最终画布(统一 scale,全部用逻辑坐标绘制)
const canvas = createCanvas(W * pixelRatio, totalH * pixelRatio);
const ctx = canvas.getContext('2d');
ctx.scale(pixelRatio, pixelRatio);
// 背景
ctx.fillStyle = background;
ctx.fillRect(0, 0, W, totalH);
// 大标题
if (bigTitle) {
ctx.font = `bold ${titleFont}px "Noto Sans CJK SC", sans-serif`;
ctx.fillStyle = textColor;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(bigTitle, W / 2, (titleH - 26) / 2 + 2);
}
// 绘制图例行(topY 为图例区顶部逻辑坐标)
const drawLegendBlock = (topY) => {
legendRows.forEach((row, ri) => {
ctx.font = `${legendFont}px "Noto Sans CJK SC", sans-serif`;
let totalW = 0;
row.forEach(it => { totalW += swatch + sw + ctx.measureText(it.name).width + ig; });
totalW -= ig;
let cx = (W - totalW) / 2;
row.forEach(it => {
ctx.fillStyle = it.color;
ctx.fillRect(cx, topY + ri * lineH + (legendFont - swatch) / 2 + 2, swatch, swatch);
ctx.fillStyle = textColor;
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.font = `${legendFont}px "Noto Sans CJK SC", sans-serif`;
ctx.fillText(it.name, cx + swatch + sw, topY + ri * lineH + legendFont / 2 + 2);
cx += swatch + sw + ctx.measureText(it.name).width + ig;
});
} else {
let x = 0;
scaled.forEach(s => {
ctx.drawImage(s.img, x * pixelRatio, 0, s.w * pixelRatio, s.h * pixelRatio);
x += s.w + gap;
});
}
});
};
// 顶部共享图例
if (sharedLegend && legendMode === 'shared-top') {
drawLegendBlock(titleH + 4);
}
// 子图(整体下移 topOffset
cells.forEach(cell => {
ctx.drawImage(cell.img, cell.x, cell.y + topOffset, cell.w, cell.h);
});
// 底部共享图例
if (sharedLegend && legendMode === 'shared-bottom') {
drawLegendBlock(topOffset + H + 8);
}
const buffer = canvas.toBuffer('image/png');
+36
View File
@@ -494,6 +494,42 @@ body {
background: #f8fafc;
}
/* 多图合并 - 每系列配置(类型/坐标轴) */
.combine-series-cfg {
display: flex;
flex-direction: column;
gap: 6px;
margin-top: 4px;
}
.combine-series-row {
display: flex;
align-items: center;
gap: 6px;
background: #fff;
border: 1px solid var(--border);
border-radius: 6px;
padding: 4px 8px;
}
.combine-series-name {
flex: 1;
font-size: 0.8rem;
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.combine-series-row select {
max-width: 96px;
padding: 3px 6px;
border: 1px solid var(--border);
border-radius: 6px;
font-size: 0.78rem;
background: white;
}
.combine-chart-card h3 {
font-size: 0.95rem;
margin: 0;