由于项目中的曲线数据量过于庞大,用户在移动端的浏览效果不是很理想,所以将echarts数据在后台转化成图片在移动端展示。
准备工作
1、下载phantojs
https://phantomjs.org/download.html
下载对应的版本
2、下载echarts-convert.js
在github上下载的不会用,这是在网上搜集到的
(function () {
var system = require('system');
var fs = require('fs');
var config = {
// define the location of js files
JQUERY: 'jquery-3.6.0.min.js',
//ESL: 'esl.js',
ECHARTS: 'echarts.js',
// default container width and height
DEFAULT_WIDTH: '1920',
DEFAULT_HEIGHT: '200'
}, parseParams, render, pick, usage;
usage = function () {
console.log("\nUsage: phantomjs echarts-convert.js -options options -outfile filename -width width -height height"
+ "OR"
+ "Usage: phantomjs echarts-convert.js -infile URL -outfile filename -width width -height height\n");
};
pick = function () {
var args = arguments, i, arg, length = args.length;
for (i = 0; i < length; i += 1) {
arg = args[i];
if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') {
return arg;
}
}
};
parseParams = function () {
var map = {}, i, key;
if (system.args.length < 2) {
usage();
phantom.exit();
}
for (i = 0; i < system.args.length; i += 1) {
if (system.args[i].charAt(0) === '-') {
key = system.args[i].substr(1, i.length);
if (key === 'infile') {
// get string from file
// force translate the key from infile to options.
key = 'options';
try {
map[key] = fs.read(system.args[i + 1]).replace(/^\s+/, '');
} catch (e) {
console.log('Error: cannot find file, ' + system.args[i + 1]);
phantom.exit();
}
} else {
map[key] = system.args[i + 1].replace(/^\s+/, '');
}
}
}
return map;
};
render = function (params) {
var page = require('webpage').create(), createChart;
var bodyMale = config.SVG_MALE;
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.onAlert = function (msg) {
console.log(msg);
};
createChart = function (inputOption, width, height,config) {
var counter = 0;
function decrementImgCounter() {
counter -= 1;
if (counter < 1) {
console.log(messages.imagesLoaded);
}
}
function loadScript(varStr, codeStr) {
var script = $('<script>').attr('type', 'text/javascript');
script.html('var ' + varStr + ' = ' + codeStr);
document.getElementsByTagName("head")[0].appendChild(script[0]);
if (window[varStr] !== undefined) {
console.log('Echarts.' + varStr + ' has been parsed');
}
}
function loadImages() {
var images = $('image'), i, img;
if (images.length > 0) {
counter = images.length;
for (i = 0; i < images.length; i += 1) {
img = new Image();
img.onload = img.onerror = decrementImgCounter;
img.src = images[i].getAttribute('href');
}
} else {
console.log('The images have been loaded');
}
}
// load opitons
if (inputOption != 'undefined') {
// parse the options
loadScript('options', inputOption);
// disable the animation
options.animation = false;
}
// we render the image, so we need set background to white.
$(document.body).css('backgroundColor', 'white');
var container = $("<div>").appendTo(document.body);
container.attr('id', 'container');
container.css({
width: width,
height: height
});
// render the chart
var myChart = echarts.init(container[0]);
myChart.setOption(options);
// load images
loadImages();
return myChart.getDataURL();
};
// parse the params
page.open("about:blank", function (status) {
// inject the dependency js
page.injectJs(config.ESL);
page.injectJs(config.JQUERY);
page.injectJs(config.ECHARTS);
var width = pick(params.width, config.DEFAULT_WIDTH);
var height = pick(params.height, config.DEFAULT_HEIGHT);
// create the chart
var base64 = page.evaluate(createChart, params.options, width, height,config);
fs.write("base64.txt",base64);
// define the clip-rectangle
page.clipRect = {
top: 0,
left: 0,
width: width,
height: height
};
// render the image
page.render(params.outfile);
console.log('render complete:' + params.outfile);
// exit
phantom.exit();
});
};
// get the args
var params = parseParams();
// validate the params
if (params.options === undefined || params.options.length === 0) {
console.log("ERROR: No options or infile found.");
usage();
phantom.exit();
}
// set the default out file
if (params.outfile === undefined) {
var tmpDir = fs.workingDirectory + '/tmp';
// exists tmpDir and is it writable?
if (!fs.exists(tmpDir)) {
try {
fs.makeDirectory(tmpDir);
} catch (e) {
console.log('ERROR: Cannot make tmp directory');
}
}
params.outfile = tmpDir + "/" + new Date().getTime() + ".png";
}
// render the image
render(params);
}());
3、下载echarts.js
4、下载jquery-3.6.0.min.js
将以上三个文件放在同一目录下(特别重要)
5、设置echarts的模板
类似于
{
title: {
text: ‘XXXXXXXXXXXXXXXXXXXXXXXXXXX’,
textStyle: {
align: ‘center’,
color: ‘black’,
fontSize: 16,
},
top: ‘5%’,
left: ‘center’,
},
color:‘green’,
xAxis: {
show:true,
position: ‘top’,
type: ‘category’,
data: [’-80.000’, ‘-79.800’, ‘-79.600’, ‘-79.400’, ‘-79.200’, ‘-79.000’, ‘-78.800’, ‘-78.600’, ‘-78.400’, ‘-78.200’, ‘-78.000’, ‘-77.800’, ‘-77.600’, ‘-77.400’, ‘-77.200’],
name:“m:s\nms”,
nameLocation:‘center’,
nameTextStyle:{
color:“black”,
padding: [0, 0, 0, -1600]
},
nameGap:10,
nameRotate:0,
axisLine:{
onZero:false
},
axisTick: {
alignWithLabel: true
},
axisLabel: {
interval:‘auto’,//代表显示所有x轴标签显示
showMinLabel: true, // 强制显示最小值标签
showMaxLabel: true, // 强制显示最大值标签
lineStyle: {
color:‘black’,
},
}
},
yAxis: {
type: ‘value’,
min: null,
max: null,
splitLine: {
show: false,
lineStyle: {
type: ‘dotted’
},
interval: function (index,value) {
if(value==“0:00\n0.000”){
return true;
}
return false;
}
},
//格式化
margin:0, // 清除默认间距
padding:[0,10,0,0], // 右边内边距10
},
series: [
{
data: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
type: “line”,
smooth:true,//折点是圆弧状的
symbol: ‘circle’, //折点设定为实心点
symbolSize: 3, //设定实心点的大小
markLine: { // 样式可以单独设置,也可以一起设置
symbol: “none”,
silent: true, // 鼠标移上是否有响应(线变粗)
data: [
{
yAxis: “0”,
//type: “min/max/average” // 特殊的标注类型,用于标注最大值最小值等。
lineStyle: { // 线的样式
color: “#EFCA2A”,
width: 1,
opacity: 0.8
},
label: { // 文字的样式,默认是白色,有时候文字不显示,可能是颜色的问题
color: “#77D048”
}
},
{
xAxis:“0.000”,
lineStyle: { // 线的样式
color: “#ef004c”,
width: 1,
opacity: 0.8
},
label: { // 文字的样式,默认是白色,有时候文字不显示,可能是颜色的问题
color: “#ef004c”
}
}
],
}
}
]
}
以上表示的是echarts中的option内容
java代码
package com.echarts.echartsutil.util;
import java.io.*;
public class EchartsUtil {
private static String jsPath = "C:\\Users\\abc\\Desktop\\phantomjs-2.1.1-windows\\1111\\echarts-convert.js";
private static String echartJsPath = "C:\\Users\\abc\\Desktop\\phantomjs-2.1.1-windows\\1111\\option.js";
private static String picturePath = "C:\\Users\\abc\\Desktop\\phantomjs-2.1.1-windows\\1111\\picture\\test2.png";
public static void main(String[] args) throws Exception{
// 拼接命令
String cmd = "C:\\Users\\abc\\Desktop\\phantomjs-2.1.1-windows\\bin\\phantomjs " + jsPath + " -infile " + echartJsPath + " -outfile " + picturePath;
// 执行命令,window系统需要额外配置
String osName = System.getProperties().getProperty("os.name");
Process process = null;
if (osName.toLowerCase().startsWith("win")) {
process = Runtime.getRuntime().exec("cmd /c " + cmd);
} else { process = Runtime.getRuntime().exec(cmd);
}
// 打印控制台信息
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
}
}
生成图片
在linux下同理。