我正在尝试使用矩形选择框(使用this example)在mousemove上的d3树中选择节点。当svg处于正常规模时它工作正常。如果我增加或减少比例值,它将无法正常工作。
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);
}
});
答案 0 :(得分:2)
我建议您使用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