力導向圖

主要利用d3.layout.force()生成的力導向布局器

 const nodes = [{name: 1}, {name: 2}, {name: 3}, {name: 4}, {name: 5}, {name: 1}, {name: 2}, {name: 3}, {name: 4}, {name: 5}, {name: 6}, {name: 7}];
    const edges = [{source: 0, target: 1}, {source: 0, target: 2}
        , {source: 0, target: 3}
        , {source: 0, target: 4}
        , {source: 4, target: 5}
        , {source: 6, target: 2}
        , {source: 6, target: 3}
        , {source: 7, target: 4}
        , {source: 8, target: 5}
        , {source: 10, target: 5}
        , {source: 11, target: 7}
        , {source: 9, target: 6}];
    const width = 700, height = 500, padding = {top: 60, left: 30};
    const svg = d3.select("body").append("svg").attr("width", width + padding.left * 2).attr("height", height + padding.top * 2);
    const force = d3.layout.force().nodes(nodes).links(edges).size([width, height]).linkDistance(120).charge(-610);
    force.start();
    const color = d3.scale.category10();
    const linearColor = d3.scale.category20();
    //    創建拖拽監聽事件
    const dragEventor= force.drag().on("dragstart",function (d) {
//        每個節點都有一個fixed節點 設為true即固定
//        此固定是指不會受力的影響彈回去 不是不能拖動了
        d.fixed = true;
    }).on("dragend",function (d,i) {
//        拖拽結束后變成原來的顏色
        d3.select(this).transition().attr("fill",color(i));
    }).on("drag",function (d,i) {
//        拖拽時變色
        d3.select(this).transition().attr("fill",linearColor(i));
    });
    const lines = svg.selectAll(".force-line").data(edges).enter()
        .append("line")
        .attr("class", "force-line");
    const circles = svg.selectAll(".force-circle").data(nodes).enter()
        .append("circle")
        .attr("class", "force-circle")
//        開啟拖拽
        .call(force.drag)
//        綁定拖拽事件
        .call(dragEventor);
    const texts = svg.selectAll(".force-text").data(nodes).enter()
        .append("text")
        .attr("dy", ".3em")
        .attr("class", "force-text");
    force.on("tick", function () {
        lines.attr("x1", function (d) {
                return d.source.x
            }).attr("y1", function (d) {
            return d.source.y
        }).attr("x2", function (d) {
            return d.target.x
        }).attr("y2", function (d) {
            return d.target.y
        });
        circles.attr("r", 20)
            .attr("cx", function (d) {
                return d.x
            }).attr("fill", function (d, i) {
            return color(i);
        }).attr("cy", function (d) {
            return d.y
        });
        texts.attr("x", function (d) {
            return d.x
        }).attr("y", function (d) {
            return d.y
        }).text(function (d) {
            return d.name;
        });
    });

結果:

image.png

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容