4

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

 2 years ago
source link: https://segmentfault.com/a/1190000040906016
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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


一: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图表变为图片


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK