d3.js缩放无溢出

d3.js zoom without overflow

本文关键字:溢出 缩放 js d3      更新时间:2023-09-26

我有一个具有固定节点的力定向图。我已允许缩放图形:

var force = d3.layout.force()
         .on("tick", tick);
var zoom = d3.behavior.zoom()
    .scaleExtent([0, 50])
    .on("zoom", zoomed);
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(zoom);
var graphGroup = svg.append("g")
                  .attr("height", graphHeight)
                  .attr("width", graphWidth)
                  .attr("class", "graph-group")
                  .attr("transform", "translate(" + margin + "," + margin + ")");
graphGroup.append("rect")
                  .attr("x", 0)
                  .attr("y", 0)
                  .attr("height", graphHeight)
                  .attr("class", "graph-limit")
                  .attr("width", graphWidth);
...
function zoomed() {
    graphContainer.attr("transform", "translate(" + t + ")scale(" + d3.event.scale + ")");
}

我想将图的zoomscaletranslation)限制在类为"graph-limit"的矩形内。我试着让overflow:hidden有风格,但没有成功。知道吗?

编辑:这是一把小提琴http://jsfiddle.net/Lxc43v8d/20/

这就是你可以做到的。

使用与矩形外尺寸完全相同的剪辑路径:

//make a clip path
svg.append("defs").append("svg:clipPath")
        .attr("id", "clip")
        .append("svg:rect")
        .attr("id", "clip-rect")
        .attr("x", 0)
                  .attr("y", 0)
                  .attr("height", graphHeight)
                  .attr("width", graphWidth);

对于包含矩形的组,所有节点和链接都添加了类似的剪辑路径

var graphGroup = svg.append("g")
            .attr("clip-path", "url(#clip)")//add the clip path
                  .attr("height", graphHeight)
                  .attr("width", graphWidth)
                  .attr("class", "graph-group");

此处的工作代码

希望这能有所帮助!