2016-08-05 64 views
1

我想使用矩形選擇框(使用this example)在mousemove上的我的d3樹中選擇節點。當svg處於正常範圍時,它工作正常。如果我增加或減少比例值,它不會按預期工作。使用矩形選擇框在縮放期間選擇SVG元素不工作:d3.js

var translateCoords = d3.transform(d3.select("#svgGroup").attr("transform")); 
      translateX = translateCoords.translate[0]; 
      translateY = translateCoords.translate[1]; 
      scaleX = translateCoords.scale[0]; 
      scaleY = translateCoords.scale[1]; 
//where svgGroup is the main svg g element, 
     radius is radius of inner nodes 

      d3.selectAll('g.node-element >circle.inner').each(function(state_data, i) { 
       var tCoords = d3.transform(d3.select(this.parentNode).attr("transform")); 
       tX = tCoords.translate[0]; 
       tY = tCoords.translate[1]; 
       if( 
        !d3.select(this).classed("selectedNode") && 
        tX+translateX*scaleX -radius>=d.x && tX+translateX*scaleX -radius<=parseInt(d.x)+parseInt(d.width)&& 
        tY+translateY*scaleY-radius>=d.y && tY+translateY*scaleY+radius<=d.y+d.height 
       ) { 
        d3.select(this.parentNode) 
        .classed("selection", true) 
        .classed("selectedNode", true); 
       } 
      }); 

這裏是jsFiddle demo

回答

1

我會建議你使用getScreenCTM計算轉換和縮放點。

因此而不是做尋找translated + scaled point這個繁重的計算(坦率地說是非常艱難的理解!):

tX = tCoords.translate[0]; 
tY = tCoords.translate[1]; 
// console.log(tX+translateX +":"+d.x) 
if (!d3.select(this).classed("selectedNode") && 
    tX + translateX * scaleX >= d.x && tX + translateX * scaleX <= parseInt(d.x) + parseInt(d.width) && 
    tY + translateY * scaleY >= d.y && tY + translateY * scaleY <= d.y + d.height 
) 

我會建議你使用getScreenCTM,使您的生活更輕鬆:

var point = svg.node().createSVGPoint(); //create a point 
var ctm = d3.select(this.parentNode).node().getScreenCTM(); //get screen ctm of the group 
point.matrixTransform(ctm); //apply the transition + scale to the point 
tX = point.matrixTransform(ctm).x; // the new translated+scaled point x 
tY = point.matrixTransform(ctm).y; // the new translated+scaled point y 
//now do your usual comparison to find selection 
if (!d3.select(this).classed("selectedNode") && 
    tX >= d.x && tX <= (parseInt(d.x) + parseInt(d.width)) && 
    tY >= d.y && tY <= (parseInt(d.y) + parseInt(d.height)) 
) { 

工作代碼here

+1

工作:)謝謝:) – Jerry