echarts 自定义系列 实现分块的柱状图

1,171 阅读1分钟

因项目需求,需要写个echarts自定义的图表,非常头疼!!

这里做个备份收藏

复制代码到echarts编辑器里可以直接看效果

image.png

option = {
    backgroundColor: 'black',
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            data: [120, 200, 130, 80, 70, 110, 130],
            type: 'custom',
            renderItem: function (params, api) {
                const topAxis = api.coord([api.value(0), api.value(1)]);
                const bottomAxis = api.coord([api.value(0), 0]);

                const totalHeight = bottomAxis[1] - topAxis[1];
                const gap = 3; // 每个格子间的间距
                const height = 10;
                const width = 20;
                const count = Math.round(totalHeight / (height + gap));

                const itemStyle = api.style()

                const rects = Array.from({ length: count }, (_, index) => {
                    const realHeight = bottomAxis[1] - (height + gap) * index;
                    return {
                        type: 'rect', //使用自定义注册类型!!!!!
                        transition: 'all',
                        x:0,
                        scaleX:1,
                        scaleY:1,
                        originX:bottomAxis[0] - 10 + width/2,
                        originY:realHeight - 10 + height/2,
                        enterFrom:{
                            scaleX:0.1,
                            scaleY:0.1,
                            style: { opacity:0},
                        },
                        enterAnimation:{
                            delay:10 * index
                        },
                        updateAnimation:{
                            delay:10 * index
                        },
                        shape: {
                            x: bottomAxis[0] - height,
                            y: realHeight - height,
                            width,
                            height
                        },
                        style: {
                            fill: echarts.color.lift(itemStyle.fill, 1 - realHeight / api.getHeight())
                        }
                    };
                });

                return {
                    type: 'group',
                    x: 0,
                    y: 0,
                    children: rects
                };
            },
            itemStyle: {
                color: 'blue'
            }
        }
    ]
};

参考文献:juejin.cn/post/706639…