使用行

时间:2015-11-12 15:44:22

标签: d3.js force-layout

我创建了3组不同的力布局:

(function () {
    /****** Functions *******
     ************************/
    var rand = function (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    /****** Variables *******
     ************************/
    var i,
        color,
        width  = 400,
        height = 400,
        forces = [],
        coords,
        _linksData, _nodesData,
        mainContainer;

    /** Coordinates of groups **/
    coords = [
        [0, 0],
        [width, 0],
        [width * 2, 0],
    ];

    color = d3.scale.category10();

    /****** Main SVG container *******
     *********************************/
    mainContainer = d3.select("#main-container").append("svg")
        .attr("width", 1165)
        .attr("height", 650)
        .append("g");

    for (i = 0; i < 3; i++) {
        forces[i] = d3.layout.force();

        (function () {
            /****** Generate Random Data for one Group *******
             *************************************************/

            /** Random amount of circles with random radius **/
            _nodesData = d3.range(rand(25, 45)).map(function (d, i) {
                return {
                    id     : i,
                    radius : rand(6, 18)
                }
            });

            /**
             Add children to group with 0 radius in order to have d3
             position it in center and put all other circles in its orbit
             **/
            _nodesData.push({
                children : d3.range(_nodesData.length),
                radius   : 0
            });

            /** Add links **/
            _linksData = d3.layout.tree().links(_nodesData);


            /****** Create Group Container *******
             *************************************/
            var groupContainer = mainContainer.append("g")
                .attr('class', 'group')
                .attr('id', 'group' + i)
                .attr('transform', 'translate(' + coords[i][0] + ',' + coords[i][1] + ')')
                .on('mouseenter', function () {
                    var index = d3.select(this).attr('id').replace('group', '');
                    // console.log(index);
                    forces[index].alpha(.25);
                });

            var nodesObjects = groupContainer.selectAll(".node");
            var linksObjects = groupContainer.selectAll(".link")

            /****** Force Layout ******/
            forces[i].linkDistance(function () {
                    return rand(110, 130)
                })
                .charge(function () {
                    return -rand(150, 200)
                })
                .gravity(0.1 + 1 / rand(10, 50))
                .size([width, height])
                .on("tick", tick)
                .nodes(_nodesData)
                .links(_linksData)
                .start();

            /****** links ******/
            // linksObjects = linksObjects.data(_linksData)
            //     .enter()
            //     .append("line").attr('class', 'link')
            //
            // ;

            /****** Create nodes ******/
            nodesObjects = nodesObjects.data(_nodesData, function (d) {
                    return d.id;
                })
                .enter().append("g")
                .attr("class", "node")
                .on('mouseover', function () {
                    d3.select(this).moveToFront();
                });


            /****** Create circles ******/
            nodesObjects.append("circle")
                .attr("r", function (d) {
                    return d.radius;
                }).style("fill", color(i));


            function tick() {
                linksObjects.attr({
                    x1 : function (d) {
                        return d.source.x;
                    },
                    y1 : function (d) {
                        return d.source.y;
                    },
                    x2 : function (d) {
                        return d.target.x;
                    },
                    y2 : function (d) {
                        return d.target.y;
                    }
                });

                nodesObjects.attr("transform", function (d) {
                    return "translate(" + d.x + "," + d.y + ")";
                });
            }

        })();
    }
}())

http://jsfiddle.net/dmitrychuba/h69wqvcy/2/

结果:

问题

有没有办法添加连接圆圈的线条并保持圆圈的位置?

澄清:线应该连接到圆圈,即在圆圈移动时更新它们的位置

http://jsfiddle.net/dmitrychuba/h69wqvcy/2/

更新

通过添加行布局并更新其在tick事件上的位置

来实现

1 个答案:

答案 0 :(得分:0)

关于阻止圈子移动的问题:

您可以在一段时间后调用force.alpha(0)停止移动,然后resume() mouseout上的 var groupContainer = mainContainer.append("g") .attr('class', 'group') .attr('id', 'group' + i) .attr('transform', 'translate(' + coords[i][0] + ',' + coords[i][1] + ')') .on('mouseenter', function () { var index = d3.select(this).attr('id').replace('group', ''); // console.log(index); forces[index].alpha(0.25); setTimeout(function () { forces[index].alpha(0); }, 1000); }) .on('mouseout', function () { var index = d3.select(this).attr('id').replace('group', ''); // console.log(index); forces[index].resume(); }); 布局。根据你想做的事情,这可能对你有用:http://jsfiddle.net/h69wqvcy/3/

Last Exception Backtrace:
0   CoreFoundation                  0x23b75856 __exceptionPreprocess + 122
1   libobjc.A.dylib                 0x354eadfa objc_exception_throw + 34
2   CoreFoundation                  0x23b7b020 -[NSObject(NSObject) doesNotRecognizeSelector:] + 184
3   CoreFoundation                  0x23b78c7a ___forwarding___ + 698
4   CoreFoundation                  0x23aa81a4 _CF_forwarding_prep_0 + 20
5   MyFramework                     0x002d72aa 0x2c9000 + 58026
6   MyFramework                     0x002edd12 0x2c9000 + 150802
7   CoreData                        0x238f0346 developerSubmittedBlockToNSManagedObjectContextPerform + 174
8   libdispatch.dylib               0x35c0fe16 _dispatch_client_callout + 18
9   libdispatch.dylib               0x35c18e82 _dispatch_barrier_sync_f_slow + 538
10  CoreData                        0x238f0242 -[NSManagedObjectContext performBlockAndWait:] + 202
11  MyFramework                     0x002edb50 0x2c9000 + 150352
12  MyFramework                     0x002ed596 0x2c9000 + 148886
13  MyFramework                     0x0030273c 0x2c9000 + 235324
14  MyFramework                     0x002e8c52 0x2c9000 + 130130
15  libdispatch.dylib               0x35c0fe2a _dispatch_call_block_and_release + 6
16  libdispatch.dylib               0x35c18840 _dispatch_async_redirect_invoke + 1364
17  libdispatch.dylib               0x35c1b80c _dispatch_root_queue_drain + 1568
18  libdispatch.dylib               0x35c1b1e6 _dispatch_worker_thread3 + 90
19  libsystem_pthread.dylib         0x35da4e08 _pthread_wqthread + 1020
20  libsystem_pthread.dylib         0x35da49f8 start_wqthread + 4

如果在超时到期之前发生鼠标输出,您应该清除超时。