Javascript 清除d3.brush时如何调用函数?

Javascript 清除d3.brush时如何调用函数?,javascript,d3.js,Javascript,D3.js,为了详细说明这一点,假设我们有一个典型的d3笔刷用例,类似于。 当我单击笔刷外部的任何位置时,笔刷将被清除。因此,我希望在触发该事件时执行一个函数。 相关代码与Mike的示例非常相似。使用您提到的示例,您必须向overlay rect添加一个单击处理程序,并跟踪是否有笔刷集 svg.append("g") .attr("class", "brush") .call(d3.brushX() .extent([[0, 0], [width, height]])

为了详细说明这一点,假设我们有一个典型的d3笔刷用例,类似于。 当我单击笔刷外部的任何位置时,笔刷将被清除。因此,我希望在触发该事件时执行一个函数。
相关代码与Mike的示例非常相似。

使用您提到的示例,您必须向overlay rect添加一个单击处理程序,并跟踪是否有笔刷集

svg.append("g")
    .attr("class", "brush")
    .call(d3.brushX()
        .extent([[0, 0], [width, height]])
        .on("brush", brushed))
    .selectAll(".overlay")
        .on("mousedown touchstart", brushOverlay);

var brushSet = false;
function brushed() {
  if (d3.event.sourceEvent.type === "brush") return;
  var d0 = d3.event.selection.map(x.invert),
      d1 = d0.map(d3.timeDay.round);

  // If empty when rounded, use floor instead.
  if (d1[0] >= d1[1]) {
    d1[0] = d3.timeDay.floor(d0[0]);
    d1[1] = d3.timeDay.offset(d1[0]);
  }

  d3.select(this).call(d3.event.target.move, d1.map(x));
  brushSet = true;
}

function brushOverlay() {
  if (!brushSet) return; // create a new brush region
  console.log('brush Clear');
}

来自

的自适应在您提到的示例中,笔刷被清除为由最终侦听器触发的默认行为

惯用的D3解决方案是设置一个终端侦听器,检查D3.event.selection是否为null:

这是使用Bostock代码的演示,单击画笔外部并检查控制台消息:

.axis网格.domain{ 填充:ddd; 中风:无; } .axis-x.域, .轴网格.勾选线{ 行程:fff; } .轴网格。勾选短线{ 笔画不透明度:.5; } var保证金={ 前50名, 右:40,, 底数:200, 左:40 }, 宽度=960-margin.left-margin.right, 高度=300-margin.top-margin.bottom; 变量x=d3.scaleTime .domain[新日期2013,7,1,2013,7,15-1] .rangeRound[0,宽度]; var svg=d3.selectbody.appendsvg .attrwidth,width+margin.left+margin.right .attrhight,height+margin.top+margin.bottom .附录 .attransform,translate+margin.left+,+margin.top+; svg.appendg .attrclass,轴栅格 .attrtransform,translate0,+高度+ .calld3.x .滴答声3.时间小时,12 .尺寸高度 .tickFormatfunction{ 返回null; } .selectAll.tick .classedtick小调,功能正常{ 返回d.getHours; }; svg.appendg .attrclass,轴-x .attrtransform,translate0,+高度+ .calld3.x .ticksd3.timeDay .滴答滴答 .attr文本锚定,null 。选择全部文本 .attrx,6; svg.appendg .画笔 .calld3.brushX .范围[ [0, 0], [宽度、高度] ] .刷,刷 .ONED,功能{ 如果!d3.event.selection console.log您单击了画笔外侧 }; 功能刷{ 如果d3.event.sourceEvent.type==画笔返回; 变量d0=d3.event.selection.mapx.invert, d1=d0.mapd3.timeDay.round; //如果圆形时为空,则使用地板代替。 如果d1[0]>=d1[1]{ d1[0]=d3.时间日.楼层0[0]; d1[1]=d3.时间日.偏移量d1[0]; } d3.选择this.calld3.event.target.move,d1.mapx; }
请发布您迄今为止尝试过的代码,并阅读其中的建议。尽管存在明显的问题,但这是一个有趣的问题,与填充此标签的无聊问题不同。我希望OP能在这上面下点功夫。
brush.on("end", function() {
    if(!d3.event.selection){
        //your function here;
    }
});