一、效果
二、方法
一、svg转png生成
该方法生成的图表有关文字部分会向上偏移,暂不清楚原因,legend可用graphic手动生成以解决文字向上偏移问题
exports.generateImage = function (options, width, height, theme) {
console.log("GENERATE IMAGE")
console.log(`WIDTH: ${width}`)
console.log(`HEIGHT: ${height}`)
console.log(`THEME: ${theme}`)
console.log(`OPTIONS: ${JSON.stringify(options)}`)
const canvas = createCanvas(width, height)
let chart = echarts.init(null, null, {
renderer: 'svg', // 必须使用 SVG 模式
ssr: true, // 开启 SSR
width: width, // 需要指明高和宽
height: height
});
chart.setOption(options);
let svgDataURL = chart.getSvgDataURL();
svgDataURL = decodeURIComponent(svgDataURL);
// svgDataURL = svgDataURL.slice(33);
// svgDataURL = `data:image/svg+xml;base64,${btoa(svgDataURL)}`;
let image = new Image();
image.src = svgDataURL;
let ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
let dataURL = canvas.toBuffer();
chart.dispose();
chart = null;
return dataURL;
}
二、canvas容器生成
该方法生成图表文字不会偏移,但option过大时会生成失败,暂不清楚原因,生成失败时可使用方法一
exports.generateImageCanvas = function (options, width, height, theme) {
console.log("GENERATE IMAGE")
console.log(`WIDTH: ${width}`)
console.log(`HEIGHT: ${height}`)
console.log(`THEME: ${theme}`)
console.log(`OPTIONS: ${JSON.stringify(options)}`)
const canvas = createCanvas(width, height)
// ECharts 可以直接使用 node-canvas 创建的 Canvas 实例作为容器
let chart = echarts.init(canvas,null);
// let chart = echarts.init(null, null, {
// renderer: 'svg', // 必须使用 SVG 模式
// ssr: true, // 开启 SSR
// width: width, // 需要指明高和宽
// height: height
// });
chart.setOption(options);
let buffer = canvas.toBuffer();
chart.dispose();
chart = null;
return buffer
}
三、代码
https://gitee.com/sea-sun/echarts-node