Last active
August 23, 2024 03:34
-
-
Save pissang/4c32ee30e35c91336af72b129a1a4a73 to your computer and use it in GitHub Desktop.
Server side SVG rendering of ECharts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
更新:新版[email protected]已经提供零依赖的SSR解决方案。
const echarts = require('echarts'); // In SSR mode the first parameter does not need to be passed in as a DOM object const chart = echarts.init(null, null, { renderer: 'svg', // must use SVG mode ssr: true, // enable SSR width: 400, // need to specify height and width height: 300 }); // setOption as normal chart.setOption({ xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [120, 200, 150, 80, 70, 110, 130], type: 'bar' } ] }); // Output string const svgStr = chart.renderToSVGString();
太牛了,对我很有帮助!不需要什么jsdom了
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I get an error message if I use Nodejs:
See also apache/echarts#19670