Echarts图例legend过多,采用翻页处理

问题:
图例可以跟地图有联动效果,用来当列表使用,与地图有联动效果,简直太棒了,但是echarts图例太多,实在太占用空间,遮挡图表,又无法移动legend层。当屏幕小,满屏幕都是图例呀。。。如下图,头疼。

image.png

翻阅echarts相关文档,百度,Q群等途径寻找解决方法,都没有得到想要答案。于是鼓起勇气尝试修改源码。
开始的想法是:右边一列,不换行显示,出现滚动条,可以向下滚动。后来研究了echarts源码,觉得在canvas上加滚动条有点困难,所以选择了 向下翻页 的方式。

效果图:

image.png

原理

echarts创建legend层是先创建每一条图例,再计算位置,全部渲染出来。发现echarts里一段主要代码,就是这里实现了"图例换行"

// Wrap when width exceeds maxHeight or meet a `newline` group
if (nextY > maxHeight || child.newline) {
    x += currentLineMaxSize + gap;
    y = 0;
    nextY = moveY;
    currentLineMaxSize = rect.width;
}
else {
    currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
}

那么,是不是可以把 ”换行“ 变成 “换页”! .oh,good idea,get ! 于是这么干!

步骤如下:

为了避免 改动 会引起其他问题。通过自定义新的字段参数控制。
主要需要改动以下几个地方:

1.html页面中改动

我在初始化echarts的div标签下面添加<div class="js-eclegend-tool" style="position: absolute;right: 20px;top: 40%"></div>,用于存放上下翻页按钮,下面会用到。我写在echarts容器下面,css样式决定它的位置,代码如下:

<div class="ibox">
        <!--初始化echarts实例的容器-->
    <div id="eBaiduMap" class="ibox-size" style="width: 100%;"></div>
        <!--用于存放上下翻页按钮.js-eclegend-tool容器,页面中的修改只需增加下面这一句-->
    <div class="js-eclegend-tool" style="position: absolute;right: 20px;top: 40%"></div>
</div>

2.修改option配置

实例化echarts时,修改option配置,即添加pagemode: true,留意注释为//注意的地方

//modify by danhuan
legend: {
    orient: 'vertical', //注意
    right:0,
    top: 0, //注意
    //bottom:0,
    //left:0,
    //width:200,
    pagemode: true, //注意,自定义的字段,开启图例分页模式,只有orient: 'vertical'时才有效
    height:"100%",
    data: legendData,
    itemHeight:18,
    itemWidth: 18,
    textStyle: {
        fontWeight: 'bolder',
        fontSize: 12,
        color:'#fff'
    },
    inactiveColor:'#aaa',
    //padding: [20, 15],
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    shadowColor: 'rgba(0, 0, 0, 0.5)',
    shadowBlur: 5,
    zlevel: 100
},

3.修改echarts源码,总共两处修改

第一处修改,在源码中找到以下代码:

image.png

为了你们方便复制查找,我把该截图的代码粘贴出来,即:

layout: function (group, componentModel, api) {
                var rect = layout.getLayoutRect(componentModel.getBoxLayoutParams(), {
                    width: api.getWidth(),
                    height: api.getHeight()
                }, componentModel.get('padding'));
                layout.box(
                    componentModel.get('orient'),
                    group,
                    componentModel.get('itemGap'),
                    rect.width,
                    rect.height
                );

                positionGroup(group, componentModel, api);
            },

找到这几行代码,修改为以下代码:

layout: function (group, componentModel, api) {
    var rect = layout.getLayoutRect(componentModel.getBoxLayoutParams(), {
        width: api.getWidth(),
        height: api.getHeight()
    }, componentModel.get('padding'));

    /*modify by danhuan 为了避免影响到其他模块,传参数判断修改 legend 是否要分页  s*/
    if(componentModel.get('pagemode')){//如果 legend 启用分页 modify by danhuan
        layout.box(
            componentModel.get('orient'),
            group,
            componentModel.get('itemGap'),
            rect.width,
            rect.height,
            componentModel.get('pagemode') //modify by danhuan
        );
    }
    if(!componentModel.get('pagemode')){
        layout.box(
            componentModel.get('orient'),
            group,
            componentModel.get('itemGap'),
            rect.width,
            rect.height
        );
    }
    /*modify by danhuan 传参数判断修改 legend 是否要分页  e*/

    positionGroup(group, componentModel, api);
},

这样做的目的是为了将步骤2的自定义参数 pagemode: true 传进echarts ,为了避免有其他方法调用layout方法导致其他图表错误,所以用了判断if(componentModel.get('pagemode')){...},有参数 pagemode: true 时,才会进入改动的代码。

第二处修改:

找到以下代码function boxLayout(orient, group, gap, maxWidth, maxHeight)...截图如下:


image.png

将该函数修改为:

function boxLayout(orient, group, gap, maxWidth, maxHeight,pagemode) {
    //console.log(group);
    var x = 0;
    var y = 0;
    if (maxWidth == null) {
        maxWidth = Infinity;
    }
    if (maxHeight == null) {
        maxHeight = Infinity;
    }
    var currentLineMaxSize = 0;
    group.eachChild(function (child, idx) {
        //console.log(child, idx);

        var position = child.position;
        var rect = child.getBoundingRect();
        var nextChild = group.childAt(idx + 1);
        var nextChildRect = nextChild && nextChild.getBoundingRect();
        var nextX;
        var nextY;
        if (orient === 'horizontal') {
            var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
            nextX = x + moveX;
            // Wrap when width exceeds maxWidth or meet a `newline` group
            if (nextX > maxWidth || child.newline) {
                x = 0;
                nextX = moveX;
                y += currentLineMaxSize + gap;
                currentLineMaxSize = rect.height;
            }
            else {
                currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
            }
        }
        else {
            var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);

            nextY = y + moveY;

            /*by danhuan s*/
                    if(pagemode){

                        //console.log(pagemode);
                        if (nextY > maxHeight || child.newline) {
                            var html = '<div class="js-prePage"> &lt;img style="width: 32px;height: 32px;cursor: no-drop" src="/mapout-web-visual/img/up-disable.png"  title="已经是第一页"/></div>';
                            html += '<div class="js-nextPage"> &lt;img  style="width: 32px;height: 32px;cursor: pointer" src="/mapout-web-visual/img/down-icon.png" title="下一页"/></div>';
                            $('.js-eclegend-tool').html(html);
                        }
                        else {
                            currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
                        }
                    }else{
                        //console.log(pagemode);
                        // Wrap when width exceeds maxHeight or meet a `newline` group
                        if (nextY > maxHeight || child.newline) {
                            x += currentLineMaxSize + gap;
                            y = 0;
                            nextY = moveY;
                            currentLineMaxSize = rect.width;
                        }
                        else {
                            currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
                        }
                    }
                    /*by danhuan e*/
        }

        if (child.newline) {
            return;
        }

        position[0] = x;
        position[1] = y;

        orient === 'horizontal'
            ? (x = nextX + gap)
            : (y = nextY + gap);
    });
}

修改的代码意思:在图例总高度大于legend容器高度,需要换行时, 不让其换行,而是一直向下画图例, 同时向 步骤1 建的容器$('.js-eclegend-tool')里面添加 ‘上一页’、‘下一页’ 按钮。

4.添加按钮事件

给”上一页“, ”下一页“按钮添加事件,通过echarts的setOption改变legend层的top,实现其翻页

/*=====legend 的分页控制 事件=s===*/
        var PageEvent = function (i) {
            var percent = -i * 98 + '%';
            myChart.setOption({
                legend: {
                    top: percent
                }
            });
        };

        if (option.legend.pagemode) {
            $('body').on('click', '.js-prePage', function () {

                if (clickCount > 0) {
                    clickCount = clickCount - 1;
                    PageEvent(clickCount);
                    //console.log(clickCount+'上一页');
                    $('.js-prePage img').attr({'src': '/mapout-web-visual/img/up-icon.png', 'title': '上一页'});
                    $('.js-prePage img').css('cursor','pointer');
                    //$('.js-nextPage img').attr('src','/mapout-web-visual/img/down-icon.png');
                    if(clickCount==0){
                        $('.js-prePage img').attr({'src': '/mapout-web-visual/img/up-disable.png', 'title': '已经是第一页'});
                        $('.js-prePage img').css('cursor','no-drop');
                    }
                } else {
                    //console.log(clickCount+'已经是第一页');
                    $('.js-prePage img').attr({'src': '/mapout-web-visual/img/up-disable.png', 'title': '已经是第一页'});
                    $('.js-prePage img').css('cursor','no-drop');
                }
            });
            $('body').on('click', '.js-nextPage', function () {
                clickCount = clickCount + 1;
                //console.log(clickCount);
                PageEvent(clickCount);
                $('.js-prePage img').attr({'src': '/mapout-web-visual/img/up-icon.png', 'title': '上一页'});
                $('.js-prePage img').css('cursor','pointer');
            });
        }
        /*=====legend 的分页控制 事件=e===*/

按钮图标:


up-icon.png
up-disable.png
down-icon.png
down-disable.png

以上仅个人想法,请多多指教!希望能得到您更多宝贵的想法。

已修改的echarts的github地址 :https://github.com/danhuan/echarts-changed-legend 直接使用该js,可以省略第三步骤的修改源代码

本文简书地址:http://www.jianshu.com/p/869853a7c8ce

洪丹焕 创建于 2017.05.24

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容