D3同时拖动平移和缩放

时间:2016-07-05 13:02:26

标签: javascript d3.js svg

我可以通过平移拖动工作或缩放进行平移,但我无法同时进行缩放平移和拖动。

在我看来,像d3.event.zoom一样搞砸了,因为我正在将变换转换为container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");并拖动到container.attr('transform', 'translate(' + (-viewBoxX) + ',' + (-viewBoxY) + ')scale(' + zoomLevel + ')');以保持zoomLevel,但它不会让我现在拖。

我的代码基于:http://jsfiddle.net/hzL8T/4/; Implement panning while keeping nodes draggable in d3 force layout

    var w = 1200;
    var h = 800;
    var viewBoxX = 0, viewBoxY = 0;
    var zoom = d3.behavior.zoom()
                .scaleExtent([0.7, 10])
                .on("zoom", zoomed);
    var drag = d3.behavior.drag()
                .on("dragstart", dragstarted)
                .on("drag", dragged)
                .on("dragend", dragended);
    var force = d3.layout.force()
                 .nodes(dataset.nodes)
                 .links(dataset.edges)
                 .size([w, h])
                 .linkDistance([100])
                 .charge([-240])
                 .gravity(0.07)
                 .start();

    var svg = d3.select("body")
                .append("svg")
                .attr("width", w)
                .attr("height", h)
                .call(zoom);

    svg.append('rect')
              .classed('bg', true)
              .attr('stroke', 'transparent')
              .attr('fill', 'transparent')
              .attr("x", 0)
              .attr("y", 0)
              .attr('width', w)
              .attr('height', h)
              .call(drag);

    var container = svg.append("g").classed("node-area", true);

    var node = container.selectAll(".node")
                .data(dataset.nodes)
                .enter()
                .append("g")
                .attr("class", "node")
                .call(force.drag);

   node.append("circle")
                .attr("r", 15)
                .style("fill", function(d,i){ 
                    return colors(i)
                })
                .call(force.drag);

    function zoomed() {
              zoomLevel = d3.event.scale;
              container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
            }
            function dragstarted(d) {
            }

            function dragged(d) {
                viewBoxX -= d3.event.dx;
                viewBoxY -= d3.event.dy;
                container.attr('transform', 'translate(' + (-viewBoxX) + ',' + (-viewBoxY) + ')scale(' + zoomLevel + ')');

            }

            function dragended(d) {
            }

0 个答案:

没有答案