Skip to content

Instantly share code, notes, and snippets.

@pissang
Last active March 2, 2024 15:27
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save pissang/4c32ee30e35c91336af72b129a1a4a73 to your computer and use it in GitHub Desktop.
Save pissang/4c32ee30e35c91336af72b129a1a4a73 to your computer and use it in GitHub Desktop.
Server side SVG rendering of ECharts
const echarts = require("echarts");
const Canvas = require('canvas');
const {JSDOM} = require('jsdom');
const fs = require('fs');
echarts.setCanvasCreator(() => {
return new Canvas(100, 100);
});
const {window} = new JSDOM();
global.window = window;
global.navigator = window.navigator;
global.document = window.document;
const root = document.createElement('div');
root.style.cssText = 'width: 500px; height: 500px;';
const chart = echarts.init(root, null, {
renderer: 'svg'
});
chart.setOption({
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [{
animation: false,
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
fs.writeFileSync('basic.svg', root.querySelector('svg').outerHTML, 'utf-8');
chart.dispose();
@YogeshK-Itanta
Copy link

Can you add a feature to get image buffers from SVG render like png, jpeg?

It'll be really useful to me also!

@andreasloe
Copy link

andreasloe commented Mar 2, 2024

I get an error message if I use Nodejs:

/echarts.js:123
 env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
                                                     ^

ReferenceError: window is not defined
    at detect (/home/pi/node_modules/echarts/dist/echarts.js:123:54)
    at /home/pi/node_modules/echarts/dist/echarts.js:97:9
    at /home/pi/node_modules/echarts/dist/echarts.js:22:68
    at Object.<anonymous> (/home/pi/node_modules/echarts/dist/echarts.js:25:2)
    at Module._compile (node:internal/modules/cjs/loader:1375:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1434:10)
    at Module.load (node:internal/modules/cjs/loader:1206:32)
    at Module._load (node:internal/modules/cjs/loader:1022:12)
    at Module.require (node:internal/modules/cjs/loader:1234:19)
    at require (node:internal/modules/helpers:176:18)

Node.js v21.5.0

See also apache/echarts#19670

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment