当前位置: 首页 > ops >正文

ECharts 图表生成示例

 1、前端部署node.js服务代码如下:

const express = require('express');
const { createCanvas } = require('canvas');
const echarts = require('echarts');
const bodyParser = require('body-parser');const app = express();
const port = 3000;app.use(bodyParser.json({ limit: '10mb' }));app.post('/render', (req, res) => {try {const { width = 800, height = 600, option } = req.body;// 创建一个空的 codes 对象const codes = {};// 使用 Function 构造器执行传入的 JS 配置代码const func = new Function('codes', option);func(codes);// 获取配置对象const config = codes.value;if (!config) {throw new Error('配置对象 codes.value 未定义');}// 创建画布并渲染const canvas = createCanvas(width, height);const chart = echarts.init(canvas);chart.setOption(config);// 返回 PNG 图像res.set('Content-Type', 'image/png');res.send(canvas.toBuffer());} catch (error) {console.error('渲染错误:', error.message);res.status(500).send(error.message);}
});app.listen(port, () => {console.log(`图表渲染服务运行在 http://localhost:${port}`);
});

2、后端访问请求数据,直接下载生成图片


import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;import java.io.File;
import java.util.HashMap;
import java.util.Map;public class EChartsRenderer {private static final String RENDER_SERVICE_URL = "http://localhost:3000/render";/*** 渲染ECharts图表为PNG字节数组(使用Hutool优化)*/public static byte[] renderChart(String config,int width,int height,boolean transparent) {// 使用Hutool构建JSON请求体Map<String, Object> paramMap = new HashMap<>();paramMap.put("width", width);paramMap.put("height", height);paramMap.put("transparent", transparent);paramMap.put("option", config); // 自动转换JSON// 发送HTTP POST请求HttpResponse response = HttpRequest.post(RENDER_SERVICE_URL).header("Content-Type", "application/json").body(JSONUtil.toJsonStr(paramMap)) // 自动序列化为JSON字符串.timeout(30 * 1000) // 30秒超时.execute();// 处理响应if (response.isOk()) {return response.bodyBytes();} else {String errorMsg = "图表渲染失败: HTTP " + response.getStatus() + " - " + response.body();throw new RuntimeException(errorMsg);}}/*** 渲染ECharts图表为PNG字节数组(默认大小)*/public static byte[] renderChart(String config) {return renderChart(config, 800, 600, false);}public static void main(String[] args) {// 准备ECharts配置(与之前相同)String echartsConfig = "codes.value = {\n" +"    xAxis: {\n" +"        type: 'category',\n" +"        data: ['2021', '2022', '2023', '2024', '2025']\n" +"    },\n" +"    yAxis: {\n" +"        type: 'value',\n" +"        max: 40,\n" +"        axisLabel: {\n" +"            formatter: '{value}亿美元'\n" +"        }\n" +"    },\n" +"    series: [\n" +"        {\n" +"            data: [5, 12, 24, 34, 50],\n" +"            type: 'line',\n" +"            itemStyle: {\n" +"                color: '#4CAF50'\n" +"            },\n" +"            label: {\n" +"                show: true,\n" +"                position: 'top',   // 标签显示在曲线顶部\n" +"                formatter: '{c}亿美元'  // 显示数值和单位\n" +"            }\n" +"        }\n" +"    ]\n" +"};";// 渲染图表byte[] chartImage = EChartsRenderer.renderChart(echartsConfig);// 保存图片(示例)FileUtil.writeBytes(chartImage, new File("D:\\app\\echarts-chart.png"));System.out.println("图表已保存到D:\\app\\echarts-chart.png");}
}

http://www.xdnf.cn/news/14197.html

相关文章:

  • CentOS7报错:Cannot find a valid baseurl for repo: base/7/x86_64
  • day034-rsync异地容灾
  • org.springframework.cloud.openfeign 组件解释
  • JAVA实战开源项目:在线课程管理系统 (Vue+SpringBoot) 附源码
  • 超强人工智能解决方案套件InfiniSynapse:精准的业务理解、对各种数据源进行全模态联合智能分析--部署安装@Ubuntu22.04 @Docker
  • 【Z Arcade】八色部落战争各阵营兵种分析级排名
  • 【C语言练习】096. 使用C语言实现简单的游戏逻辑
  • RK AndroidFramework 内置应用可,卸载,恢复出厂设置恢复安装
  • 蓝桥杯国赛前一晚知识点准备(十六届python)
  • 多线程——锁
  • Keepalived 高可用
  • 基于SpringBoot+JSP开发的招投标采购信息平台
  • 插入点(position) 和对齐点(AlignmentPoint)详解——CAD c#二次开发
  • 59、定制化原理-SpringBoot定制化组件的几种方式
  • STM32 vs RT1176:正交编码器实现原理与工程实践全解析
  • AI-调查研究-06-“冷水澡”对生理健康的影响与机制【下篇】
  • LangChain自动化工作流实战教程:从任务编排到智能决策
  • FOC无刷电机控制:ABZ与SPI信号选择
  • 【0.1 漫画计算机组成原理】
  • Vue3 + TypeScript + Element Plus 使用【设置表格列宽,组合式函数 hook】在原有页面实现表格列宽设置本地持久化实例总结
  • MySQL(75)如何进行增量备份和恢复?
  • 2.4 机器人运动控制
  • sd调试记录(标准库 + keil + RL-FlashFS):
  • 算法题:一个数组,找出其中最小连续的子数组,是的这个子数组排序后,整体数组...
  • [直播推流] 编译 librtmp 库
  • 【QT】控件一(QWidget、Button、Label)
  • 设计模式汇总
  • 从易用性出发的教育场景音量调节技术方案
  • Dify 本地化部署教程(含常见问题与解决方案)
  • 【Day48】