在水平画笔上使用.filter()

时间:2018-01-29 02:45:37

标签: javascript d3.js brush

我需要创建一个d3画笔,它只允许右侧的扩展/收缩。即我需要阻止左移动和扩展/收缩的默认行为。

docs看起来这可以通过filter函数(?)实现 - 但我没有看到如何实现上述用例。在this example中,如果我将var brush更改为

var brush = d3.brushX()
    .extent([[0, 0], [width, height]])
    .on("start brush", brushed)
    .filter(function(){return event.button;})
    ;

添加.filter这也阻止了右侧的点击: - )

1 个答案:

答案 0 :(得分:3)

如果您检查鼠标事件的目标,那么使用.filter()的方法将起作用。您的一维水平画笔将由D3构建如下:

<rect class="overlay" pointer-events="all" cursor="crosshair" x="0" y="0" width="960" height="500"></rect>
<rect class="selection" cursor="move" fill="#777" fill-opacity="0.3" stroke="#fff" shape-rendering="crispEdges" x="112" y="194" width="182" height="83"></rect>
<rect class="handle handle--e" cursor="ew-resize" x="289" y="189" width="10" height="93"></rect>
<rect class="handle handle--w" cursor="ew-resize" x="107" y="189" width="10" height="93"></rect>

鉴于此结构,您需要过滤掉针对<rect class="handle handle--w"/><rect class="selection"/>的事件:

.filter(function() {
  return !d3.event.button 
    && !d3.select(d3.event.target).classed("handle--w")
    && !d3.select(d3.event.target).classed("selection");
})

这将过滤掉针对左手柄的事件(即具有类<rect>的{​​{1}})以及针对选择本身的事件。看看工作demo

此外,您必须调整光标的样式,以便在将鼠标左手柄和所选区域悬停时不会改变其外观。

handle--w