d3 - 画笔/平移缩放 - 禁用上部x轴上的平移

时间:2016-09-08 06:39:58

标签: javascript d3.js zoom brush panning

我使用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]);

}

谢谢!

1 个答案:

答案 0 :(得分:2)

要禁用主图表上的平移,请禁用矩形中的mousedown缩放:

所以这段代码:

svg.append("rect")
  .attr("class", "zoom")
  .attr("width", width)
  .attr("height", height)
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  .call(zoom);

从矩形

中删除mousedown缩放
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);

工作代码here