Echarts是百度发布的一套优秀的浏览器端图表控件,Echarts是基于html5的cavens绘图实现。而使用server端生成图片无法借用浏览器端渲染。通用的做法有两种:

  1. 是用headless浏览器渲染,例如Phantomjs
  2. node-cavens渲染,类似node-echarts等方案,虽然Phantomjs也是基于Nodejs。

环境准备:

下载Phantomjs

从 http://phantomjs.org/download.html 下载指定版本,配置好环境变量,当

$ phantomjs -v
2.1.1

就算完成了。

相关依赖下载

jquery,echarts从相关CDN或者官网下载。

主流程

使用命令:

$ phantomjs echarts-convert.js -infile option.js -outfile t.png
Echarts.options has been parsed
The images have been loaded
render complete:t.png
  • echarts-convert.js 类似一个浏览器页面,执行js的入口。
  • infile 注入参数
  • outfile 输出的文件

echarts-convert.js


(function () {
var system = require('system');
var fs = require('fs');
var config = {
// define the location of js files
JQUERY: 'jquery.1.9.1.min.js',
ESL: 'esl.js',
ECHARTS: 'echarts-all.js',
// default container width and height
DEFAULT_WIDTH: '600',
DEFAULT_HEIGHT: '700'
}, 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];
}
}
}
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);
}());

option.js

{
title : {
text: '某地区蒸发量和降水量',
subtext: '纯属虚构'
},
tooltip : {
trigger: 'axis'
},
legend: {
data:['蒸发量','降水量']
},
toolbox: {
show : true,
feature : {
mark : {show: true},
dataView : {show: true, readOnly: false},
magicType : {show: true, type: ['line', 'bar']},
restore : {show: true},
saveAsImage : {show: true}
}
},
calculable : true,
xAxis : [
{
type : 'category',
data : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'蒸发量',
type:'bar',
data:[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
markPoint : {
data : [
{type : 'max', name: '最大值'},
{type : 'min', name: '最小值'}
]
},
markLine : {
data : [
{type : 'average', name: '平均值'}
]
}
},
{
name:'降水量',
type:'bar',
data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
markPoint : {
data : [
{name : '年最高', value : 182.2, xAxis: 7, yAxis: 183, symbolSize:18},
{name : '年最低', value : 2.3, xAxis: 11, yAxis: 3}
]
},
markLine : {
data : [
{type : 'average', name : '平均值'}
]
}
}
]
};

运行结果:

外部资源无法加载

{
title : {
text: '某地区蒸发量和降水量',
subtext: '纯属虚构'
},
tooltip : {
trigger: 'axis'
},
legend: {
data:['蒸发量','降水量']
},
toolbox: {
show : true,
feature : {
mark : {show: true},
dataView : {show: true, readOnly: false},
magicType : {show: true, type: ['line', 'bar']},
restore : {show: true},
saveAsImage : {show: true}
}
},
calculable : true,
xAxis : [
{
type : 'category',
data : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'蒸发量',
type:'bar',
data:[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
markPoint : {
data : [
{type : 'max', name: '最大值'},
{type : 'min', name: '最小值'}
]
},
markLine : {
data : [
{type : 'average', name: '平均值'}
]
}
},
{
name:'降水量',
type:'bar',
data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
markPoint : {
data : [
{name : '年最高', value : 192.2, xAxis: 7, yAxis: 183, symbolSize:18,symbol:"image://./organ/gall.png"},
{name : '年最低', value : 2.3, xAxis: 11, yAxis: 3}
]
},
markLine : {
data : [
{type : 'average', name : '平均值'}
]
}
}
]
};

执行后,

没有symbol丢失。怀疑是symbol的图片无法外部加载。

Echarts服务端生成图片的更多相关文章

  1. Highcharts结合PhantomJS在服务端生成高质量的图表图片

    项目背景 最近忙着给部门开发一套交互式的报表系统,来替换原有的静态报表系统. 老系统是基于dotnetCHARTING开发的,dotnetCHARTING的优势是图表类型丰富,接口调用简单,使用时只需 ...

  2. 如何将phantomjs单独部署在服务端

    如何将phantomjs单独部署在服务端 文章目录 一. 容我分析(lao dao)几句 二. 服务端 Look here 服务端phantomjs搭建 web端搭建及如何调用phantomjs 三. ...

  3. 【分享】Vue 资源典藏(UI组件、开发框架、服务端、辅助工具、应用实例、Demo示例)

    Vue 资源典藏,包括:UI组件 开发框架 服务端 辅助工具 应用实例 Demo示例 element ★11612 - 饿了么出品的Vue2的web UI工具套件 Vux ★7503 - 基于Vue和 ...

  4. 使用Node搭建reactSSR服务端渲染架构

    如题:本文所讲架构主要用到技术栈有:Node, Express, React, Mobx, webpack4, ES6, ES7, axios, ejs,  log4js, scss,echarts, ...

  5. Vue UI组件 开发框架 服务端 辅助工具 应用实例 Demo示例

    Vue UI组件 开发框架 服务端 辅助工具 应用实例 Demo示例 element ★11612 - 饿了么出品的Vue2的web UI工具套件 Vux ★7503 - 基于Vue和WeUI的组件库 ...

  6. Node.js 服务端处理图片

    Node 服务端处理图片 服务端进行图片处理是很常见的需求,但是Node在这一块相对来说比较薄弱.找了几个比较常见的模块来解决问题. gm GraphicsMagick for node 使用Open ...

  7. Swift3.0服务端开发(一) 完整示例概述及Perfect环境搭建与配置(服务端+iOS端)

    本篇博客算是一个开头,接下来会持续更新使用Swift3.0开发服务端相关的博客.当然,我们使用目前使用Swift开发服务端较为成熟的框架Perfect来实现.Perfect框架是加拿大一个创业团队开发 ...

  8. 关于如何提高Web服务端并发效率的异步编程技术

    最近我研究技术的一个重点是java的多线程开发,在我早期学习java的时候,很多书上把java的多线程开发标榜为简单易用,这个简单易用是以C语言作为参照的,不过我也没有使用过C语言开发过多线程,我只知 ...

  9. Socket聊天程序——服务端

    写在前面: 昨天在博客记录自己抽空写的一个Socket聊天程序的初始设计,那是这个程序的整体设计,为了完整性,今天把服务端的设计细化记录一下,首页贴出Socket聊天程序的服务端大体设计图,如下图: ...

随机推荐

  1. linux中Vi编辑器使用

    1.如需要编辑aaa.txt文件: vi  aaa.txt   就可以进入到   aaa.txt文件中, 输入  i   进入到编辑模式, 按 Esc 退出编辑模式  , :wq   保存退出编辑模式 ...

  2. 【CodeChef】Prime Distance On Tree

    vjudge 给定一棵边长都是\(1\)的树,求有多少条路径长度为质数 树上路径自然是点分治去搞,但是发现要求是长度为质数,总不能对每一个质数都判断一遍吧 自然是不行的,这个东西显然是一个卷积,我们合 ...

  3. java 泛型数组列表

    如下代码: package com.company; import java.lang.reflect.Array; import java.util.ArrayList; public class ...

  4. Mysql基础知识—索引

    公司最近开始尝试进行改革,如何活跃团队气氛.开发就给我们说了一些算是科普类的数据库知识,下面参杂自己的理解,方便自己后续翻看.   1.什么是索引 索引在MySQL中也叫做“键”,是存储引擎用于快速找 ...

  5. P2904 [USACO08MAR]跨河River Crossing

    题目描述 Farmer John is herding his N cows (1 <= N <= 2,500) across the expanses of his farm when ...

  6. 51 Nod 1107 斜率小于0的连线数量 (转换为归并求逆序数或者直接树状数组,超级详细题解!!!)

    1107 斜率小于0的连线数量 基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题   二维平面上N个点之间共有C(n,2)条连线.求这C(n,2)条线中斜率小于0的线 ...

  7. NYOJ 18 The Triangle 填表法,普通dp

    题目链接: http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=18 The Triangle 时间限制:1000 ms  |  内存限制:6553 ...

  8. PCL利用RANSAC自行拟合分割平面

    利用PCL中分割算法. pcl::SACSegmentation<pcl::PointXYZ> seg; ,不利用法线参数,只根据模型参数得到的分割面片,与想象的面片差距很大, pcl:: ...

  9. MongoDB4.0+版本安装

    >>>首先要下载MongoDB软件安装包, MongoDB社区版官网下载 >>>双击msi安装文件进行安装,点击"Next" >>& ...

  10. Golang设计模式—简单工厂模式(Simple Factory Pattern)

    Golang设计模式--简单工厂模式 背景 假设我们在做一款小型翻译软件,软件可以将德语.英语.日语都翻译成目标中文,并显示在前端. 思路 我们会有三个具体的语言翻译结构体,或许以后还有更多,但现在分 ...