-
Notifications
You must be signed in to change notification settings - Fork 86
/
index.js
83 lines (73 loc) · 1.98 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var echarts = require("echarts");
var Canvas = require("canvas-prebuilt");
var fs = require('fs');
var path = require('path');
/**
* @param config = {
width: 500 // Image width, type is number.
height: 500 // Image height, type is number.
option: {}, // Echarts configuration, type is Object.
//If the path is not set, return the Buffer of image.
path: '', // Path is filepath of the image which will be created.
}
*
*/
module.exports = function (config) {
if (config.canvas) {
Canvas = config.canvas;
}
var ctx = new Canvas(128, 128);
if (config.font) {
ctx.font = config.font;
}
echarts.setCanvasCreator(function () {
return ctx;
});
var chart, option = {
title: {
text: 'test'
},
tooltip: {},
legend: {
data: ['test']
},
xAxis: {
data: ["a", "b", "c", "d", "f", "g"]
},
yAxis: {},
series: [{
name: 'test',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
let defaultConfig = {
width: 500,
height: 500,
option,
enableAutoDispose: true
}
config = Object.assign({}, defaultConfig, config)
config.option.animation = false;
chart = echarts.init(new Canvas(parseInt(config.width, 10), parseInt(config.height, 10)));
chart.setOption(config.option);
if (config.path) {
try {
fs.writeFileSync(config.path, chart.getDom().toBuffer());
if(config.enableAutoDispose){
chart.dispose();
}
console.log("Create Img:" + config.path)
} catch (err) {
console.error("Error: Write File failed" + err.message)
}
} else {
var buffer = chart.getDom().toBuffer();
try{
if(config.enableAutoDispose){
chart.dispose();
}
}catch(e){}
return buffer;
}
}