legend.js 19.6 KB
Newer Older
K
kener 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/**
 * echarts组件:图例
 * Copyright 2013 Baidu Inc. All rights reserved.
 *
 * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
 * @author Kener (@Kener-林峰, linzhifeng@baidu.com)
 *
 */
define(function (require) {
    /**
     * 构造函数
     * @param {Object} messageCenter echart消息中心
     * @param {ZRender} zr zrender实例
     * @param {Object} option 图表参数
     * @param {Object=} selected 用于状态保持
     */
    function Legend(messageCenter, zr, option, selected) {
        var Base = require('./base');
        Base.call(this, zr);

        var ecConfig = require('../config');
        var zrArea = require('zrender/tool/area');

        var self = this;
        self.type = ecConfig.COMPONENT_TYPE_LEGEND;

        var legendOption;                       // 图例选项,共享数据源
        var _zlevelBase = self.getZlevelBase();

        var _itemGroupLocation = {};    // 图例元素组的位置参数,通过计算所得x, y, width, height

        var _colorIndex = 0;
        var _colorMap = {};
        var _selectedMap = {};

36 37 38 39 40
        var icon = require('zrender/shape').get('icon');
        for (var k in legendIcon) {
            icon.define('legendicon' + k, legendIcon[k]);
            //console.log('legendicon' + k, legendIcon[k])
        }
K
kener 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

        function _buildShape() {
            _itemGroupLocation = _getItemGroupLocation();

            _buildBackground();
            _buildItem();

            for (var i = 0, l = self.shapeList.length; i < l; i++) {
                self.shapeList[i].id = zr.newShapeId(self.type);
                zr.addShape(self.shapeList[i]);
            }
        }

        /**
         * 构建所有图例元素
         */
        function _buildItem() {
            var data = legendOption.data;
            var dataLength = data.length;
            var itemName;
            var itemType;
            var itemShape;
            var textShape;
            var font = self.getFont(legendOption.textStyle);

            var zrWidth = zr.getWidth();
            var lastX = _itemGroupLocation.x;
            var lastY = _itemGroupLocation.y;
            var itemWidth = legendOption.itemWidth;
            var itemHeight = legendOption.itemHeight;
            var itemGap = legendOption.itemGap;
            var color;

            if (legendOption.orient == 'vertical'
                && legendOption.x == 'right'
            ) {
                lastX = _itemGroupLocation.x
                        + _itemGroupLocation.width
                        - itemWidth;
            }

            for (var i = 0; i < dataLength; i++) {
                itemName = data[i];
                itemType = _getSeriesByName(itemName);
                if (itemType) {
                    itemType = itemType.type;
                } else {
88
                    itemType = 'bar';
K
kener 已提交
89 90 91 92 93 94 95
                }
                color = getColor(itemName);

                if (legendOption.orient == 'horizontal') {
                    if (zrWidth - lastX < 200   // 最后200px做分行预判
                        && (itemWidth + 5
                         + zrArea.getTextWidth(itemName, font)
K
kener 已提交
96
                         + (i < dataLength - 1 ? itemGap : 0))
K
kener 已提交
97 98 99 100 101 102 103 104 105 106 107
                        >= zrWidth - lastX
                    ) {
                        lastX = 0;
                        lastY += itemHeight + itemGap;
                    }
                }

                // 图形
                itemShape = _getItemShapeByType(
                    lastX, lastY,
                    itemWidth, itemHeight,
108 109
                    (_selectedMap[itemName] ? color : '#ccc'),
                    itemType
K
kener 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
                );
                itemShape._name = itemName;
                itemShape.onclick = _legendSelected;
                self.shapeList.push(itemShape);

                // 文字
                textShape = {
                    shape : 'text',
                    zlevel : _zlevelBase,
                    style : {
                        x : lastX + itemWidth + 5,
                        y : lastY,
                        color : _selectedMap[itemName]
                                ? legendOption.textStyle.color
                                : '#ccc',
                        text: itemName,
                        textFont: font,
                        textBaseline: 'top'
                    },
                    clickable : true
                };

                if (legendOption.orient == 'vertical'
                    && legendOption.x == 'right'
                ) {
                    textShape.style.x -= (itemWidth + 10);
                    textShape.style.textAlign = 'right';
                }

                textShape._name = itemName;
                textShape.onclick = _legendSelected;
                self.shapeList.push(textShape);

                if (legendOption.orient == 'horizontal') {
                    lastX += itemWidth + 5
                             + zrArea.getTextWidth(itemName, font)
                             + itemGap;
                }
                else {
                    lastY += itemHeight + itemGap;
                }
            }
        }

        function _buildBackground() {
            var pTop = legendOption.padding[0];
            var pRight = legendOption.padding[1];
            var pBottom = legendOption.padding[2];
            var pLeft = legendOption.padding[3];

            self.shapeList.push({
                shape : 'rectangle',
                zlevel : _zlevelBase,
                hoverable :false,
                style : {
                    x : _itemGroupLocation.x - pLeft,
                    y : _itemGroupLocation.y - pTop,
                    width : _itemGroupLocation.width + pLeft + pRight,
                    height : _itemGroupLocation.height + pTop + pBottom,
                    brushType : legendOption.borderWidth === 0
                                ? 'fill' : 'both',
                    color : legendOption.backgroundColor,
                    strokeColor : legendOption.borderColor,
                    lineWidth : legendOption.borderWidth
                }
            });
        }

        /**
         * 根据选项计算图例实体的位置坐标
         */
        function _getItemGroupLocation() {
            var data = legendOption.data;
            var dataLength = data.length;
            var itemGap = legendOption.itemGap;
            var itemWidth = legendOption.itemWidth + 5; // 5px是图形和文字的间隔,不可配
            var itemHeight = legendOption.itemHeight;
K
kener 已提交
187
            var font = self.getFont(legendOption.textStyle);
K
kener 已提交
188 189 190 191 192 193 194 195 196
            var totalWidth = 0;
            var totalHeight = 0;

            if (legendOption.orient == 'horizontal') {
                // 水平布局,计算总宽度
                for (var i = 0; i < dataLength; i++) {
                    totalWidth += itemWidth
                                  + zrArea.getTextWidth(
                                        data[i],
K
kener 已提交
197
                                        font
K
kener 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
                                    )
                                  + itemGap;
                }
                totalWidth -= itemGap;      // 减去最后一个的itemGap
                totalHeight = itemHeight;
            }
            else {
                // 垂直布局,计算总高度
                totalHeight = (itemHeight + itemGap) * dataLength;
                totalHeight -= itemGap;     // 减去最后一个的itemGap;
                var maxWidth = 0;
                for (var i = 0; i < dataLength; i++) {
                    maxWidth = Math.max(
                        maxWidth,
                        zrArea.getTextWidth(
                            data[i],
K
kener 已提交
214
                            font
K
kener 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
                        )
                    );
                }
                totalWidth = itemWidth + maxWidth;
            }

            var x;
            var zrWidth = zr.getWidth();
            switch (legendOption.x) {
                case 'center' :
                    x = Math.floor((zrWidth - totalWidth) / 2);
                    break;
                case 'left' :
                    x = legendOption.padding[3] + legendOption.borderWidth;
                    break;
                case 'right' :
                    x = zrWidth
                        - totalWidth
                        - legendOption.padding[1]
                        - legendOption.borderWidth;
                    break;
                default :
                    x = legendOption.x - 0;
K
kener 已提交
238
                    x = isNaN(x) ? 0 : x;
K
kener 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
                    break;
            }

            var y;
            var zrHeight = zr.getHeight();
            switch (legendOption.y) {
                case 'top' :
                    y = legendOption.padding[0] + legendOption.borderWidth;
                    break;
                case 'bottom' :
                    y = zrHeight
                        - totalHeight
                        - legendOption.padding[2]
                        - legendOption.borderWidth;
                    break;
                case 'center' :
                    y = Math.floor((zrHeight - totalHeight) / 2);
                    break;
                default :
                    y = legendOption.y - 0;
K
kener 已提交
259
                    y = isNaN(y) ? 0 : y;
K
kener 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
                    break;
            }

            // 水平布局的横向超长自动分行,纵布局超长不考虑
            if (legendOption.orient == 'horizontal' && totalWidth > zrWidth) {
                totalWidth = zrWidth;
                if (x < 0) {
                    x = 0;
                }
                totalHeight += totalHeight + 10;
            }


            return {
                x : x,
                y : y,
                width : totalWidth,
                height : totalHeight
            };
        }

        /**
         * 根据名称返回series数据
         */
        function _getSeriesByName(name) {
            var series = option.series;
K
kener 已提交
286 287
            var hasFind;
            var data;
K
kener 已提交
288 289 290 291 292 293 294 295
            for (var i = 0, l = series.length; i < l; i++) {
                if (series[i].name == name) {
                    // 系列名称优先
                    return series[i];
                }

                if (series[i].type == ecConfig.CHART_TYPE_PIE) {
                    // 饼图得查找里面的数据名字
K
kener 已提交
296 297
                    hasFind = false;
                    data = series[i].data;
K
kener 已提交
298 299 300 301 302 303 304 305 306 307
                    for (var j = 0, k = data.length; j < k; j++) {
                        if (data[j].name == name) {
                            hasFind = true;
                            break;
                        }
                    }
                    if (hasFind) {
                        return series[i];
                    }
                }
K
kener 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
                else if (series[i].type == ecConfig.CHART_TYPE_FORCE) {
                    // 力导布局查找categories配置
                    hasFind = false;
                    data = series[i].categories;
                    for (var j = 0, k = data.length; j < k; j++) {
                        if (data[j].name == name) {
                            data = data[j];
                            data.type = ecConfig.CHART_TYPE_FORCE;
                            hasFind = true;
                            break;
                        }
                    }
                    if (hasFind) {
                        return data;
                    }
                }
K
kener 已提交
324 325 326 327 328
            }
            return;
        }

        function _getItemShapeByType(x, y, width, height, color, itemType) {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
            var itemShape = {
                shape : 'icon',
                zlevel : _zlevelBase,
                style : {
                    iconType : 'legendicon' + itemType,
                    x : x,
                    y : y,
                    width : width,
                    height : height,
                    color : color,
                    strokeColor : color,
                    lineWidth : 2
                },
                clickable : true
            };
            
            // 特殊设置
K
kener 已提交
346 347
            switch (itemType) {
                case 'line' :
348 349
                    itemShape.style.brushType = 'stroke';
                    break;
K
kener 已提交
350
                case 'k' :
351 352 353 354 355 356 357 358 359
                    itemShape.style.brushType = 'both';
                    itemShape.style.color = self.deepQuery(
                        [ecConfig], 'k.itemStyle.normal.color'
                    ) || '#fff';
                    itemShape.style.strokeColor = color != '#ccc' 
                        ? self.deepQuery(
                              [ecConfig], 'k.itemStyle.normal.lineStyle.color'
                          ) || '#ff3200'
                        : color;
K
kener 已提交
360
            }
361
            return itemShape;
K
kener 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        }

        function _legendSelected(param) {
            var itemName = param.target._name;
            _selectedMap[itemName] = !_selectedMap[itemName];
            messageCenter.dispatch(
                ecConfig.EVENT.LEGEND_SELECTED,
                param.event,
                {selected : _selectedMap}
            );
        }

        function init(newOption) {
            if (!self.deepQuery([newOption], 'legend.data')) {
                return;
            }

            option = newOption;

            option.legend = self.reformOption(option.legend);
            // 补全padding属性
            option.legend.padding = self.reformCssArray(
                option.legend.padding
            );

            legendOption = option.legend;

            self.clear();

            _selectedMap = {};

            var data = legendOption.data || [];
            var finalData = [];
            var itemName;
            var serie;
            var color;
            for (var i = 0, dataLength = data.length; i < dataLength; i++) {
                itemName = data[i];
                serie = _getSeriesByName(itemName);
                if (!serie) {
                    continue;
                } else {
                    finalData.push(data[i]);
                    color = self.deepQuery(
                        [serie], 'itemStyle.normal.color'
                    );
                    if (color) {
                        setColor(itemName, color);
                    }
                    _selectedMap[itemName] = true;
                }
            }
            if (finalData.length > 0) {
                legendOption.data = finalData;
                if (selected) {
                    for (var k in selected) {
                        _selectedMap[k] = selected[k];
                    }
                }
                _buildShape();
            }
        }

        /**
         * 刷新
         */
        function refresh() {
            legendOption = option.legend;
            self.clear();
            _buildShape();
        }

        function setColor(legendName, color) {
            _colorMap[legendName] = color;
        }

        function getColor(legendName) {
            if (!_colorMap[legendName]) {
                _colorMap[legendName] = zr.getColor(_colorIndex++);
            }
            return _colorMap[legendName];
        }
K
kener 已提交
444 445 446 447
        
        function hasColor(legendName) {
            return _colorMap[legendName] ? _colorMap[legendName] : false;
        }
K
kener 已提交
448

K
kener 已提交
449
        function add(name, color){
K
kener 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
            legendOption.data.push(name);
            setColor(name,color);
            _selectedMap[name] = true;
        }

        function del(name){
            var data = legendOption.data;
            var finalData = [];
            var found = false;
            for (var i = 0, dataLength = data.length; i < dataLength; i++) {
                if (found || data[i] != name) {
                    finalData.push(data[i]);
                } else {
                    found = true;
                    continue;
                }
            }
            legendOption.data = finalData;
        }
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
        
        /**
         * 特殊图形元素回调设置
         * @param {Object} name
         * @param {Object} itemShape
         */
        function getItemShape(name) {
            var shape;
            for (var i = 0, l = self.shapeList.length; i < l; i++) {
                shape = self.shapeList[i];
                if (shape._name == name && shape.shape != 'text') {
                    return shape;
                }
            }
        }
        
        /**
         * 特殊图形元素回调设置
         * @param {Object} name
         * @param {Object} itemShape
         */
        function setItemShape(name, itemShape) {
            var shape;
            for (var i = 0, l = self.shapeList.length; i < l; i++) {
                shape = self.shapeList[i];
                if (shape._name == name && shape.shape != 'text') {
                    if (!_selectedMap[name]) {
                        itemShape.style.color = '#ccc';
                        itemShape.style.strokeColor = '#ccc';
                    }
                    zr.modShape(shape.id, itemShape)
                }
            }
        }
K
kener 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

        function isSelected(itemName) {
            if (typeof _selectedMap[itemName] != 'undefined') {
                return _selectedMap[itemName];
            }
            else {
                // 没在legend里定义的都为true啊~
                return true;
            }
        }

        self.init = init;
        self.refresh = refresh;
        self.setColor = setColor;
        self.getColor = getColor;
K
kener 已提交
518
        self.hasColor = hasColor;
K
kener 已提交
519 520
        self.add = add;
        self.del = del;
521 522
        self.getItemShape = getItemShape;
        self.setItemShape = setItemShape;
K
kener 已提交
523 524 525 526
        self.isSelected = isSelected;

        init(option);
    }
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
    
    var legendIcon = {
        line : function (ctx, style) {
            var dy = style.height / 2;
            ctx.moveTo(style.x,     style.y + dy);
            ctx.lineTo(style.x + style.width,style.y + dy);
        },
        pie : function (ctx, style) {
            var x = style.x;
            var y = style.y;
            var width = style.width;
            var height = style.height;
            var sector = require('zrender/shape').get('sector');
            sector.buildPath(ctx, {
                x : x + width / 2,
                y : y + height + 2,
                r : height + 2,
                r0 : 6,
                startAngle : 45,
                endAngle : 135
            });
        },
        k : function (ctx, style) {
            var x = style.x;
            var y = style.y;
            var width = style.width;
            var height = style.height;
            var candle = require('zrender/shape').get('candle');
            candle.buildPath(ctx, {
                x : x + width / 2,
                y : [y + 1, y + 1, y + height - 6, y + height],
                width : width - 6
            });
        },
        bar : function (ctx, style) {
            ctx.rect(style.x, style.y + 1, style.width, style.height - 2);
K
kener 已提交
563 564 565
        },
        force : function(ctx, style) {
            require('zrender/shape').get('icon').get('circle')(ctx, style);
566 567 568
        }
    }
    
569 570
    require('../component').define('legend', Legend);
    
K
kener 已提交
571 572 573 574
    return Legend;
});