如何在没有默认调用函数d3.behavior.zoom()和d3.behavior.drag()的情况下在D3.js中创建缩放,拖动函数

时间:2014-10-27 16:41:07

标签: javascript d3.js zoom drag

我一直在强制布局中使用D3.js图。我一直在使用带有javascript语言的Leap Motion设备。

我的问题是我无法创建不使用为鼠标编写的默认方法的缩放和拖动功能,如d3.behavior.zoom(),d3.behavior.drag()。

例如,我有这种缩放方法:

 function zoom(graph) {
    graph.zoom =
        d3.behavior.zoom()
            .x(graph.x)
            .y(graph.y)
            .scaleExtent([0.1, 10])
            .on("zoom", function () {
                if (d3.event) {
                    graph.scale = d3.event.scale;
                    graph.translate = d3.event.translate;
                    graph.scaledNormalLength = graph.defaultNormalLength / graph.scale;
                }

                d3.select("svg").selectAll(".router").each(function (d) {
                    if ((graph.scale <= graph.zoomShrinkCondition && d.physicalRole == "router") || (graph.scale > graph.zoomShrinkCondition && d.physicalRole == "cloud"))
                        if (d.locked == undefined || !d.locked) {
                            graph.nodeZoom(d);
                        }
                });

                //remove tooltip
                graph.mouseOut();
                //calculate positions - graph will freeze without this
                graph.tick();


            });
}

这个拖动功能

function drag(graph) {
    graph.drag =
        d3.behavior.drag()
            .on("dragstart", function (d) {
                d.fixed = true;
                d3.select(this).classed("fixed", true);
                d3.event.sourceEvent.stopPropagation();
            })
            .on("drag", function (d) {
                //remove tooltip
                graph.mouseOut();

                //compute coordinates of dragged node (NOTE: if some coordinates are wrong, it is probably because of simulate() function)
                d.px += d3.event.dx / graph.scale;
                d.py += d3.event.dy / graph.scale;

                //compute coordinate of children if they are not hidden
                if (d.physicalRole == "router") {
                    setNodePosition(d, d3.event);
                }

                //compute coordinates of children if they are hidden
                if (d.physicalRole == "cloud") {
                    d._children.forEach(function (ch) {
                        ch.px += d3.event.dx / graph.scale;
                        ch.py += d3.event.dy / graph.scale;
                        setNodePosition(ch, d3.event);
                    });
                }
                graph.getForce().resume()
            });

    function setNodePosition(node, event) {
        if (node.children)
            node.children.forEach(function (ch) {
                setNodePosition(ch, event);
                ch.px += event.dx / graph.scale;
                ch.py += event.dy / graph.scale;
            })
    }
}

有没有办法在不调用d3.behavior函数的情况下创建这些方法?非常感谢你的想法。

0 个答案:

没有答案