Peekyou
Peekyou

Reputation: 471

d3.js zoom without overflow

I have a force directed graph with fixed nodes. I have allowed zoom in the graph :

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 + ")");
}

I would like to limit the zoom (scale and translation) of the graph within the rectangle with class "graph-limit". I've tried to put overflow:hidden in style, but without success. Any idea ?

EDIT : Here a jsfiddle http://jsfiddle.net/Lxc43v8d/20/

Upvotes: 1

Views: 300

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

This is how you can do it.

Use clip path with dimension exactly same as that off the rectangle:

//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);

To the group which holds the rectangle all nodes and links add the clip path like this

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

Working code here

Hope this helps!

Upvotes: 2

Related Questions