首页 前端知识 echarts图表转图片

echarts图表转图片

2025-02-24 13:02:39 前端知识 前端哥 613 767 我要收藏

功能说明

echarts图表转图片,通过传递echarts图表的options配置参数,返回png格式的文件流或base64图片字符串,可使用node服务部署在后端运行,不依赖浏览器。

方法一

Echarts + canvas , 绘制canvas画布渲染图表,无需启动浏览器服务,返回base64图片地址或图片文件流。

const echarts = require('echarts');
const { createCanvas } = require('canvas');

const [width, height] = [500, 360];
const options = {
  aniamtion: false,
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [150, 230, 224, 218, 135, 147, 260],
      type: 'line'
    }
  ]
}

// 创建canvas画布
const canvas = createCanvas(width, height);
// 实例化echart
const chart = echarts.init(canvas, null, {
  devicePixelRatio: 2,
  backgroundColor: '#fff',
});
// 设置echarts配置
chart.setOption(options);

// 获取base64
const base64 = canvas.toDataURL('image/png');
// 获取文件流
const imgBuffer = chart.getDom().toBuffer();
方法二

Echarts svg模式,SSR渲染 , 无需安装canvas,无需启动浏览器服务,返回base64的svg地址。

const echarts = require('echarts');

const [width, height] = [500, 360]
const options = {
  aniamtion: false,
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [150, 230, 224, 218, 135, 147, 260],
      type: 'line'
    }
  ]
}

// 在 SSR 模式下第一个参数不需要再传入 DOM 对象
const chart = echarts.init(null, null, {
  renderer: 'svg', // 必须使用 SVG 模式
  ssr: true, // 开启 SSR
  width,
  height
});

chart.setOption(options);

// 输出svg字符串
const svgStr = chart.renderToSVGString();

// 输出图片到本地
// writeFileSync('bar.svg', svgStr, 'utf-8');

echarts2img

转载请注明出处或者链接地址:https://www.qianduange.cn//article/21278.html
标签
评论
发布的文章

C/C | 每日一练 (2)

2025-02-24 13:02:49

Linux性能监控工具汇总

2025-02-24 13:02:48

Python常见面试题的详解16

2025-02-24 13:02:48

QQ登录测试用例报告

2025-02-24 13:02:47

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!