echart实现关联图谱,学习备份

export default {
    echartInit: function(data, searchData, startTime, endTime) {
        var option;
        var myChart = echarts.init(document.getElementById('myDiagramDiv'));
        var nodes = [];
        var links = [];
        var paths = [];
        var startNode;
        var endNode;
        var _imgObj = {
            start: "image://./static/img/startNode.png",
            person: "image://./static/img/personNode.png",
            company: "image://./static/img/companyNode.png",
        }
        getData();
        // 获取数据
        function getData() {
            $.each(data.nodes, function(i, node) {
                var img = _imgObj.company;
                var symbolSize = [45, 45];
                if (node.key == searchData.sourceKey || node.key == searchData.targetKey) {
                    img = _imgObj.start;
                    symbolSize = [75, 75];
                } else {
                    if (node.type != 1) {
                        img = _imgObj.person;
                        symbolSize = [43, 51];
                    }
                }
                nodes.push({
                    name: node.key,
                    realname: node.text,
                    level: 0,
                    symbolSize: symbolSize,
                    symbol: img,
                    label: {
                        normal: {
                            show: true,
                            fontSize: 12,
                            position: 'bottom',
                            color: '#6e6e6e',
                            formatter: function(param) {
                                return param.data.realname.replace(/(.{15})(?=.)/g, '$1\n')
                            }
                        }
                    }
                });
            });
            $.each(data.links, function(i, link) {
                var width = 1;
                var symbol = ['none', 'arrow'];
                var color = '#616161';
                if ((link.source == searchData.sourceKey && link.target == searchData.targetKey) || (link.source == searchData.targetKey && link.target == searchData.sourceKey)) {
                    color = '#616161';
                }
                if (link.category == "double") {
                    symbol = ['arrow', 'arrow'];
                }
                if (link.strokeWidth >= 2) {
                    if (link.strokeWidth == 2) {
                        width = 2;
                    } else {
                        width = 4;
                    }
                }
                links.push({
                    source: link.source,
                    target: link.target,
                    ids: link.ids,
                    symbol: symbol,
                    lineStyle: {
                        normal: {
                            width: width,
                            color: color
                        }
                    },
                    label: {
                        normal: {
                            show: false
                        }
                    }

                });
            });
            startNode = getNodeByName(searchData.sourceKey);
            endNode = getNodeByName(searchData.targetKey);
            paths = calPath(nodes, links);
            calcPos();
            drawPath(nodes, links);
        }

        //计算节点坐标位置 
        function calcPos() {
            for (var i = 0; i < paths.length; i++) {
                for (var j = 0; j < paths[i].length; j++) {
                    for (var k = 0; k < nodes.length; k++) {
                        if (paths[i][j].name == nodes[k].name) {
                            if (j > nodes[k].level) {
                                nodes[k].level = j;
                            }
                        }
                    }
                }
            }
            var levels = [];
            $.each(nodes, function(index, node) {
                if (!levels[node.level]) {
                    levels[node.level] = [];
                }
                levels[node.level].push(node);
            });
            var levelsflag = true;
            for (var level = 0; level < levels.length; level++) {
                var sameLevelNodes = levels[level];
                if (sameLevelNodes) {
                    var centerX = myChart.getZr().getWidth();
                    var centerY = myChart.getZr().getHeight();
                    var area = { width: centerX, height: centerY };
                    var xSpan = area.width / levels.length; // x 间隔
                    $.each(sameLevelNodes, function(i, node) {
                        node.x = xSpan * level + (xSpan / 2);
                        node.y = area.height / 2;
                        if (level != 0 && level != levels.length - 1) {
                            var ySpan = 0; // y
                            if (sameLevelNodes.length == 1) {
                                ySpan = area.height / 2;
                                if (levelsflag) {
                                    node.y = 0 * ySpan + ySpan / 2;
                                    levelsflag = false;
                                } else {
                                    node.y = 1 * ySpan + ySpan / 2;
                                    levelsflag = true;
                                }
                            } else {
                                ySpan = area.height / sameLevelNodes.length;
                                node.y = i * ySpan + ySpan / 2;
                            }
                        }
                    });
                }
            }
        }

        //计算路径
        function calPath(nodes, links) {
            var paths = [];
            getNext(startNode, [startNode]);

            function getNext(node, path) {
                for (var i = 0; i < links.length; i++) {
                    if (links[i].source == node.name || links[i].target == node.name) {
                        var nextNodeName;
                        if (links[i].source == node.name) {
                            nextNodeName = links[i].target;
                        } else {
                            nextNodeName = links[i].source;
                        }
                        var nextNode = getNodeByName(nextNodeName);
                        if (!existNode(nextNode, path)) {
                            var cPath = path.concat();
                            cPath.push(nextNode);
                            if (nextNode == endNode) {
                                paths.push(cPath);
                            } else {
                                getNext(nextNode, cPath);
                            }
                        }

                    }
                }
            }
            paths = paths.sort(function(a, b) {
                return a.length - b.length;
            });
            return paths;
        }

        //画图表
        function drawPath(nodes, links) {
            myChart.clear();
            option = {
                series: [{
                    type: 'graph',
                    layout: 'none',
                    roam: true,
                    animation: false,
                    symbol: 'rect',
                    circular: { rotateLabel: true },
                    draggable: true,
                    edgeSymbolSize: [10, 10],
                    animationDurationUpdate: 1500,
                    animationEasingUpdate: 'quinticInOut',
                    data: nodes,
                    links: links
                }],
                tooltip: {
                    triggerOn: 'click', //点击
                    //triggerOn: 'mousemove', //悬浮
                    enterable: true,
                    hideDelay: 50,
                    padding: 0,
                    confine: true,
                    formatter: function(params, ticket, callback) {
                        if (params.dataType == 'edge') {
                            let param = { ids: params.data.ids };
                            UserClient.get("/HongKongController/getGoJsByDoubelTab", param)
                                .then(response => {
                                    if (response.code == 200) {
                                        let datas = response.data; //获得接口返回的数据
                                        if (startTime == null || startTime.length == 0) {
                                            startTime = "2018-01-01"
                                        }
                                        if (endTime == null || endTime.length == 0) {
                                            endTime = getNowFormatDate();
                                        }
                                        let html = '<div class="tag"> <div class="moneytitle"><div class="titletimeleft"><i class="timeimg"></i>' +
                                            '<span>' + startTime + '</span><span>—</span><span>' + endTime + '</span></div><div class="titletimeright"><span class="colorstyle">|</span>' +
                                            '<span>累计:' + formatCurrency(parseFloat(datas.totle)) + '/' + datas.totleCount + '笔</span></div></div>' +
                                            '<div class="mainmoney"><div class="mainmoneyleft"><p>' + datas.turnoutname + '</p></div><div class="mainmoneymiddle">' +
                                            '<div class="center"><div class="mainmoneymiddleinfo">' + formatCurrency(parseFloat(datas.turnout)) + '/' + datas.turnoutCount + '笔</div><div class="mainmoneymiddleimg"></div><div class="mainmoneymiddleinfo">' + formatCurrency(parseFloat(datas.turninto)) + '/' + datas.turnintoCount + '笔</div>' +
                                            '</div></div><div class="mainmoneyright"><p>' + datas.turnintoname + '</p></div></div><div class="othermoneylist"><div class="scrollcontent">';
                                        $.each(datas.data, function(key, value) {
                                            if (key != datas.data.length - 1) {
                                                html += '<div class="othermoneyone">';
                                            } else {
                                                html += '<div class="othermoneyone othermoneylast">'
                                            }
                                            //let arr = value.data.split(" ");
                                            html += '<div class="othermoneyoneleft"><p title="' + value.name1 + '">' + value.name1 + '</p></div><div class="othermoneyonemiddle"><div class="center">';
                                            if (value.arrowheadLine == 'right') {
                                                html += '<div class="othermoneyonemiddlelose">' + formatCurrency(parseFloat(value.data)) + value.currency + '</div><div class="othermoneyonemiddleloseimg"></div><div class="othermoneyonemiddletime">' + value.type + value.time + '</div>';
                                            } else {
                                                html += '<div class="othermoneyonemiddleget">' + formatCurrency(parseFloat(value.data)) + value.currency + '</div><div class="othermoneyonemiddlegetimg"></div><div class="othermoneyonemiddletime">' + value.type + value.time + '</div>';
                                            }
                                            html += '</div></div><div class="othermoneyoneright"><p title="' + value.name2 + '">' + value.name2 + '</p></div></div>';
                                        })
                                        html += '</div></div></div>'
                                        callback(ticket, html);
                                    } else {
                                        console.info(response.desc);
                                    }
                                })
                                .catch(e => {
                                    console.info(e);
                                });

                        }
                        return " ";
                    },
                    position: function(pos, params, dom, rect, size) {
                        if (params.dataType == 'edge') {
                            /*  let api = new myApi();
                             api.mouseScroll.inte($('.othermoneylist'), 10); */
                            let yPos = 0
                            let xPos = 0
                            if (pos[0] <= (size.viewSize[0] / 2)) {
                                xPos = pos[0] + 20;
                            } else {
                                xPos = pos[0] - dom.offsetWidth - 20;
                            }
                            if (pos[1] <= size.viewSize[1] - 20 - dom.offsetHeight) {
                                yPos = pos[1] + 20;
                            } else if (pos[1] <= size.viewSize[1] / 2) {
                                yPos = pos[1] - (dom.offsetWidth / 3);
                            } else if (pos[1] < 20 + dom.offsetHeight) {
                                yPos = pos[1] - (dom.offsetWidth / 3) * 2;
                            } else {
                                yPos = pos[1] - 20 - dom.offsetHeight;
                            }
                            return [xPos, yPos]
                        }
                    }
                },
            };
            myChart.setOption(option);
            initInvisibleGraphic();
            window.onresize = function() {
                myChart.resize();
            }
        }

        function getNodeByName(name) {
            for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].name == name) {
                    return nodes[i];
                }
            }
        }

        function existNode(node, nodes) {
            for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].name == node.name) {
                    return true;
                }
            }
            return false;
        }

        function initInvisibleGraphic() {
            myChart.setOption({
                graphic: echarts.util.map(option.series[0].data, function(item, dataIndex) {
                    //使用图形元素组件在节点上划出一个隐形的图形覆盖住节点
                    var x = option.series[0].data[dataIndex].symbolSize[0];
                    var tmpPos = myChart.convertToPixel({ 'seriesIndex': 0 }, [item.x, item.y]);
                    return {
                        type: 'circle',
                        position: tmpPos,
                        shape: {
                            r: x / 2
                        },
                        invisible: true,
                        draggable: true,
                        ondrag: echarts.util.curry(onPointDragging, dataIndex),
                        z: 100
                    };
                })
            });
            window.addEventListener('resize', updatePosition);
            myChart.on('graphRoam', updatePosition);
        }

        function updatePosition() {
            //更新节点定位的函数
            myChart.setOption({
                graphic: echarts.util.map(option.series[0].data, function(item, dataIndex) {
                    var tmpPos = myChart.convertToPixel({ 'seriesIndex': 0 }, [item.x, item.y]);
                    return {
                        position: tmpPos
                    };
                })
            });
        }

        function onPointDragging(dataIndex) { //节点上图层拖拽执行的函数
            var tmpPos = myChart.convertFromPixel({ 'seriesIndex': 0 }, this.position);
            option.series[0].data[dataIndex].x = tmpPos[0];
            option.series[0].data[dataIndex].y = tmpPos[1];
            myChart.setOption(option);
            updatePosition();
        }

        function getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;
            return currentdate;
        }

        function formatCurrency(num) {
            //如果存在小数点,则获取数字的小数部分
            num = num.toString();
            var cents = num.indexOf(".") > 0 ? num.substr(num.indexOf(".")) : '';
            cents = cents.length > 1 ? cents : ''; //注意:这里如果是使用change方法不断的调用,小数是输入不了的
            //获取数字的整数数部分
            num = num.indexOf(".") > 0 ? num.substring(0, (num.indexOf("."))) : num;
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
                num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
            }
            //将数据(整数部分、小数部分)整体组合返回
            return (num + cents);
        }
        //滚动条
        function myApi() {
            this.mouseScroll = {
                inte: function(obj, value) {
                    this.OBJ = obj;
                    this.addscroll(obj);
                    var outH = obj.outerHeight(),
                        oScrollcontent = obj.children(':first'),
                        contentH = oScrollcontent.outerHeight(),
                        oYscrollinnerH = outH / contentH * outH,
                        oYscrollouter = obj.find('#Yscrollouter'),
                        oYscrollinner = obj.find('#Yscrollinner');
                    obj.css({ 'position': 'relative', 'overflow': 'hidden' });
                    oScrollcontent.css('position', 'absolute');
                    if (contentH > outH) {
                        this.mousehover(obj, oYscrollouter, oYscrollinner);
                        this.mousewheel(obj, value, oScrollcontent, oYscrollinner, outH, contentH, oYscrollinnerH);
                        this.mousemoved(obj, oScrollcontent, oYscrollouter, oYscrollinner, outH, contentH, oYscrollinnerH);
                    };
                },
                addscroll: function(obj, value) {
                    obj.append('<div id="Yscrollouter"><div id="Yscrollinner"></div></div>');
                    $('#Yscrollinner').css('cursor', 'pointer');
                },
                mousehover: function(obj, outer, inner) {
                    obj.hover(function() {
                        outer.fadeIn(400);
                    }, function() {
                        outer.fadeOut(400);
                    });
                    inner.hover(function() {
                        $('body').css({
                            '-moz-user-select': 'none',
                            '-webkit-user-select': 'none',
                            '-ms-user-select': 'none',
                            '-khtml-user-select': 'none',
                            'user-select': 'none',
                        });
                    }, function() {
                        $('body').css({
                            '-moz-user-select': 'auto',
                            '-webkit-user-select': 'auto',
                            '-ms-user-select': 'auto',
                            '-khtml-user-select': 'auto',
                            'user-select': 'auto',
                        });
                    });
                },
                mousewheel: function(obj, value, O, inner, H1, H2, H3) {
                    var oScrollcontentVal = value / (H1 - H3) * (H2 - H1);
                    inner.height(H3); //滚动条高度
                    obj.on('mousewheel', function(event, delta) { //绑定滚轮事件
                        event.preventDefault(); //阻止浏览器默认为行
                        var delta = event.originalEvent.wheelDelta;
                        var oYscrollinnerTop = inner.position().top;
                        var oScrollcontentTop = O.position().top;
                        if (delta > 0) {
                            if (oYscrollinnerTop - value < 0) {
                                inner.css('top', 0);
                                O.css('top', 0);
                            } else {
                                inner.css('top', oYscrollinnerTop - value);
                                O.css('top', oScrollcontentTop + oScrollcontentVal);
                            }
                        } else {
                            if (oYscrollinnerTop + value > H1 - H3) {
                                inner.css('top', H1 - H3);
                                O.css('top', H1 - H2);
                            } else {
                                inner.css('top', oYscrollinnerTop + value);
                                O.css('top', oScrollcontentTop - oScrollcontentVal);
                            }
                        };
                    });
                    obj.on('DOMMouseScroll', function(event, delta) { //绑定滚轮事件
                        event.preventDefault(); //阻止浏览器默认为行
                        var delta = event.originalEvent.detail;
                        var oYscrollinnerTop = inner.position().top;
                        var oScrollcontentTop = O.position().top;
                        if (delta < 0) {
                            if (oYscrollinnerTop - value < 0) {
                                inner.css('top', 0);
                                O.css('top', 0);
                            } else {
                                inner.css('top', oYscrollinnerTop - value);
                                O.css('top', oScrollcontentTop + oScrollcontentVal);
                            }
                        } else {
                            if (oYscrollinnerTop + value > H1 - H3) {
                                inner.css('top', H1 - H3);
                                O.css('top', H1 - H2);
                            } else {
                                inner.css('top', oYscrollinnerTop + value);
                                O.css('top', oScrollcontentTop - oScrollcontentVal);
                            }
                        };
                    });
                },
                mousemoved: function(obj, O, outer, inner, H1, H2, H3) {
                    inner.on('mousedown', function(event) { //绑定鼠标事件
                        var clientY = event.clientY,
                            oYscrollinnerTop = inner.position().top,
                            oScrollcontentTop = O.position().top,
                            moveY = 0;
                        $(document).on('mousemove', function(event) {
                            moveY = event.clientY - clientY;
                            var oScrollcontentMove = moveY / (H1 - H3) * (H2 - H1);
                            if (oYscrollinnerTop + moveY < 0) {
                                inner.css('top', 0);
                                O.css('top', 0);
                            } else if (oYscrollinnerTop + moveY > H1 - H3) {
                                inner.css('top', H1 - H3);
                                O.css('top', H1 - H2);
                            } else {
                                inner.css('top', oYscrollinnerTop + moveY);
                                O.css('top', oScrollcontentTop - oScrollcontentMove);
                            }
                        });
                        $(document).on('mouseup', function(event) {
                            $(document).off('mousemove');
                        })

                    })
                }

            }
        }
    }
}

 

 

 

/*   var data = {
        nodes: [
          { text: "d", type: "1", key: "4" },
          { text: "e", type: "1", key: "5" },
          { text: "a", type: "1", key: "1" },
          { text: "c", type: "1", key: "3" },
          { text: "b", type: "2", key: "2" }
        ],
        links: [
          {
            strokeWidth: 2,
            ids: "7,8",
            source: "4",
            category: "",
            target: "5"
          },
          {
            strokeWidth: 2,
            ids: "7,8",
            source: "1",
            category: "",
            target: "5"
          },
          {
            strokeWidth: 1,
            ids: "6",
            source: "1",
            category: "",
            target: "4"
          },
          {
            strokeWidth: 1,
            ids: "3",
            source: "3",
            category: "",
            target: "4"
          },
          {
            strokeWidth: 2,
            ids: "4,5",
            source: "1",
            category: "",
            target: "3"
          },
          {
            strokeWidth: 2,
            ids: "2,9",
            source: "2",
            category: "double",
            target: "3"
          },
          { strokeWidth: 1, ids: "1", source: "1", category: "", target: "2" }
        ]
      };*/
      /*var searchData = {
        sourceKey: this.name_id,
        targetKey: this.trading_partner_id
      };
      detailDiagram.echartInit(data, searchData);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值