我用d3来绘制线形图。在这个例子https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172之后,我实现了一个笔刷/平移缩放。我想禁用上x轴的平移。当我点击并拖动它时,它触发了画笔。我只想在用画笔点击下x轴或使用鼠标滚轮时触发它。这是负责画笔效果的代码:
var brush = d3.brushX()
.extent([[MARGINS.left, 0], [WIDTH, HEIGHT2]])
.on("end", brushed);
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([MARGINS.left,0], [WIDTH, HEIGHT])
.extent([[MARGINS.left,0], [WIDTH, HEIGHT]])
.on("zoom", zoomed);
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
var s = d3.event.selection || xScale2.range();
xScale.domain(s.map(xScale2.invert, xScale2));
var limits = xScale.domain();
var a = parseInt(limits[0]);
var b = parseInt(limits[1]);
var data1;
if ((b-a) === screen.width) {
data1 = shrinkArray(1, b, a);
} else if((b-a) > screen.width) {
data1 = shrinkArray(parseInt((b-a)/screen.width), b, a);
} else {
data1 = data;
}
for(var i = 0; i < numberOfSignals; i++) {
if(signalBool[i]) {
focus.selectAll("#line"+i).attr("d", lineGen(data1[i]));
indexSignal = i;
}
}
focus.select(".axis--x").call(xAxis);
vis.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(WIDTH / (s[1] - s[0]))
.translate(-s[0], 0));
}
function zoomed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
var t = d3.event.transform;
xScale.domain(t.rescaleX(xScale2).domain());
for(var i = 0; i < numberOfSignals; i++) {
if(signalBool[i]) {
focus.selectAll("#line"+i).attr("d", lineGen(data[i]));
indexSignal = i;
}
}
focus.select(".axis--x").call(xAxis);
context.select(".brush").call(brush.move, xScale.range().map(t.invertX, t));
var limits = xScale.domain();
var a = parseInt(limits[0]);
var b = parseInt(limits[1]);
}
谢谢!
若要在主图形上禁用平移功能,则禁用鼠标向下缩放矩形:
所以这个代码:
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
移除矩形的鼠标向下缩放
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom).on("mousedown.zoom", null)
.on("touchstart.zoom", null)
.on("touchmove.zoom", null)
.on("touchend.zoom", null);
这里的工作代码