在D3.js中如何在点击圆圈时隐藏画笔

How to hide brush when a circle is clicked in D3.js?

本文关键字:画笔 隐藏 D3 js      更新时间:2023-09-26

我有一个散点图,点击事件和刷事件都突出显示点。如果我先在一些圆圈上刷,然后点击一个圆圈,画笔仍然是可见的。

我怎样才能使它消失,当一个单一的圆圈被点击,但仍然可用之后?

这是一个JSFiddle。

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<style>
#plot{
    border-style: solid;
    border-width: 4px;
    border-color: lightgray;
    display: inline-block;
    line-height: 0;
}
circle{
    fill: blue;
}
.highlight{
    fill: red;
}
</style>
<body>
<script src="d3.js"></script>
<div id="plot">
<script>
(function(){
    var data = [];
    for(i = 0; i < 100; i++){
        var x = Math.random();
        var y = Math.random();
        data.push({x: x, y: y});
    }
    var xScale = d3.scale.linear()
        .domain([0, 1])
        .range([0, 400]);
    var yScale = d3.scale.linear()
        .domain([0, 1])
        .range([400, 0]);
    var svg = d3.select("#plot").append("svg")
        .attr("width", 400)
        .attr("height", 400)
    var brush = d3.svg.brush()
        .x(xScale)
        .y(yScale)
        .on("brushstart", brushstart)
        .on("brushend", brushend);
    function brushstart(){
        d3.selectAll("circle")
          .classed("highlight", false);
    }
    function brushend(){
        var e = brush.extent();
        d3.selectAll("circle").filter(function(d){
            return xScale(d.x) >= xScale(e[0][0]) && 
                   yScale(d.y) <= yScale(e[0][1]) &&
                   xScale(d.x) <= xScale(e[1][0]) && 
                   yScale(d.y) >= yScale(e[1][1]);                                             
        })
        .classed("highlight", true);                       
    }
    svg.append("g")
      .classed("brush", true)
      .call(brush);
    svg.selectAll("circle")
        .data(data)
        .enter().append("circle")
        .attr("r", 6)
        .attr("cx", function(d){ return xScale(d.x) })
        .attr("cy", function(d){ return yScale(d.y) })
        .on("click", function(){
            d3.selectAll("circle").classed("highlight", false);
            d3.select(this).classed("highlight", true);
        });                                          
})();
</script>
</div>
</body>
</html> 

我可以使画笔消失与d3.selectAll("brush").remove()d3.selectAll("brush").style("display", "none"),但画笔不能使用之后。

我认为隐藏画笔的正确方法,之后仍然能够使用它,是使用brush.clear() D3 SVG控件

Like this - d3.selectAll(".brush").call(brush.clear());

小提琴