javascript - 使用矩形选择框选择 SVG 元素在缩放期间不起作用 : d3. js

标签 javascript jquery d3.js svg

我正在尝试使用矩形选择框(使用 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);
                }
            });

这是jsFiddle demo

最佳答案

我建议您使用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/

相关文章:

javascript - 使用jquery将内容包装在一个div中

pandas - 如何将我的 Pandas 数据框移动到 d3?

javascript - 在 knockout 映射中加载数据之前防止 html 加载

javascript - 如何调用类内部的方法?

javascript - 使用 tooltipster 获取要呈现的工具提示?

javascript - persistence.js add() 函数不起作用

javascript - 如何在 Controller 外使用 $http?在 AngularJS 中

javascript - D3.js 进入退出更新模式实现

javascript - D3 中的计数总和

javascript - 防止使用箭头键滚动页面,但仍允许光标在文本字段内移动?