我正在尝试使用矩形选择框(使用 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);
}
});
最佳答案
我建议您使用getScreenCTM计算平移和缩放点。
因此,与其进行繁重的计算来查找翻译+缩放点
(坦率地说,这非常难以理解!):
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
关于javascript - 使用矩形选择框选择 SVG 元素在缩放期间不起作用 : d3. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38782018/