关于echarts:将echarts生成的图表变为图片保存起来

16次阅读

共计 1324 个字符,预计需要花费 4 分钟才能阅读完成。


一:echarts

echarts 官网:https://echarts.apache.org/zh…

echarts.js 地址:https://cdn.jsdelivr.net/npm/…

二:将 echarts 生成的图表变为图片示例

1:html

<div style="width:800px;height:500px;" id="chart">
</div>

2: 生成 echarts 图表 (js),这里以柱状图为例

var chart = echarts.init(document.getElementById("chart"));
var option = {
    animation: false,
    title: {
        text: '统计',
        padding: [10, 320, 0, 320]
    },
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        name: '月份',
    },
    tooltip : {
        trigger: 'item',
        formatter: "{a} : {c}"
    },
    yAxis: {
        type: 'value',
        name: '数量',
    },
    series: [{
        name: '数量',
        data: [120, 200, 150, 80, 70, 110, 130],
        type: 'bar',
        barWidth : 50,// 柱图宽度
        label: {
            show: true,
            position: 'top'
        },
        itemStyle: {
            color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [{offset: 0, color: '#4976C5'},
                    {offset: 0.5, color: '#7496D3'},
                    {offset: 1, color: '#ECF0F9'},

                ]
            )
        },
    }
    ]
};
chart.setOption(option);

3:获取生成的柱状图的 base64 地址

// 获取 echarts 图表的 base64 地址
var baseImage = chart.getDataURL("png");

4:将生成的 base64 传到后端保存起来

(1):ajax 上传

$.ajax({
    url: url,
    type: 'post',
    data: {image:baseImage},
    success: function (json) {}});

(2):后端保留文件 (以 PHP 为例)

$image = $request->post('image');

if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {$type = $result[2];

    fullPath = '图片保留地址';

    $fileName = 'echarts.png';// 图片保留名称
    if (file_put_contents($fullPath . $fileName, base64_decode(str_replace($result[1], '', $image)))) {return '上传胜利';} else {return '图片上传失败!';}
} else{return '有效的图片文件!';}

依据如上步骤就能够实现将 echarts 图表变为图片

正文完
 0