项目需求:Java后端导出的PDF文件内需要带上echarts图表数据,所以需要用Node+canvas画布生成图表图片传给Java后端。
注:Node本身是不带canvas,所以需要安装canvas依赖。要求Node最低版本是12.0.0。本地使用版本是v14.21.2。
生成echarts图表图片的插件:https://github.com/xiaomaigou/echarts-export-server。文档有详细的介绍了。注意:部署在lunix服务器上,需要修改src/index.js内的代码,修改为chart.setOption({...config.option,fontFamily: 'SimSun'});lunix系统需要配置中文字体【SimSun宋体】,否则生成echarts图片的汉字会乱码。
下面是演示下启动echarts-export-server服务的步骤:
步骤1:克隆依赖【echarts-export-server】
git clone https://github.com/xiaomaigou/echarts-export-server
步骤2:进入文件目录后,打开命令窗口,运行npm install安装。注意:npm安装插件失败后,需要删除node_modules重新安装,建议用cnpm安装。
cd echarts-export-server
npm install //建议用cnpm安装
步骤3:安装 项目依赖canvas,由于canvas 二进制文件默认通过github下载,可能下载较慢,通过npm参数指定该模块的二进制文件下载镜像地址
npm install --unsafe-perm --canvas_binary_host_mirror=https://registry.npmmirror.com/-/binary/canvas/
步骤4:启动node服务,服务地址是:http://localhost:3000/
npm start;
//可为npm start添加watch监听文件与ignore-watch忽略监听文件命令,添加两个命令后需要pm2 delete all,再npm start监听文件才会生效
pm2 start ./src/index.js --watch --ignore-watch='test node_modules' --name echarts-export-server
步骤5:直接用【浏览器访问】或者用【接口访问】便可得到base64图片。
http://localhost:3000/?config=%7B%22width%22%3A800%2C%22height%22%3A500%2C%22option%22%3A%7B%22backgroundColor%22%3A%22%23fff%22%2C%22xAxis%22%3A%7B%22type%22%3A%22category%22%2C%22data%22%3A%5B%22Mon%22%2C%22Tue%22%2C%22Wed%22%2C%22Thu%22%2C%22Fri%22%2C%22Sat%22%2C%22Sun%22%5D%7D%2C%22yAxis%22%3A%7B%22type%22%3A%22value%22%7D%2C%22series%22%3A%5B%7B%22data%22%3A%5B666%2C777%2C888%2C333%2C1290%2C1330%2C1320%5D%2C%22type%22%3A%22line%22%7D%5D%7D%7D
//http://localhost:3000/?config={"type":"png","width":1200,"height":500,"base64":false,"download":false,"option":{"title":[{"text":"园区用电量趋势(KW.h)","top":15,"left":25,"textStyle":{"fontSize":16," fontFamily ":"SimSun"}},{"text":"本月总用量:188800KW.h","top":15,"right":300,"textStyle":{"fontSize":16}}],"tooltip":{"trigger":"axis"},"legend":{"type":"scroll","top":15,"right":30},"grid":{"left":30,"right":30,"bottom":20,"containLabel":true},"toolbox":{"right":25},"xAxis":{"type":"category","boundaryGap":false,"data":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},"yAxis":{"type":"value"},"series":[{"name":"电","type":"line","data":[33333333120,132,101,134,90,230,210,132,101,134,90,230,210]}]}}
注意:
escape() 使用转义序列替换某些字符来对字符串进行编码。
unescape() 对使用 escape() 编码的字符串进行解码。
escape('{"width":800,"height":500,"option":{"backgroundColor":"#fff","xAxis":{"type":"category","data":["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]},"yAxis":{"type":"value"},"series":[{"data":[666,777,888,333,1290,1330,1320],"type":"line"}]}}');
演示图片效果: