isapir
isapir

Reputation: 23503

Restricting d3.js zoom to container

consider the following structure:

<svg width="720" height="560" style="outline: red;">
   <g width="640" height="480" transform="translate(40,40)" style="outline: blue;">
     <g class="container" width="640" height="480">
       <!-- more stuff here... !-->
     </g>
   </g>
</svg>

so now we have two squares via the outlines, the outer one red, and the inner one blue.

I added zoom behavior on the .container but when it zooms out it goes beyond the bounds of the g element, and cover the whole svg area.

I am trying to limit the zoom so that it is restricted to the 640x480 area, and whatever falls outside that region to be hidden, so that the white margins between the red box and the blue box remain unchanged on zoom.

Currently the blue box's size is modified and consumes the margins when it expands.

How can I achieve that? see fiddle at http://jsfiddle.net/1cg16x02/2/

Upvotes: 1

Views: 992

Answers (1)

D Malan
D Malan

Reputation: 11414

If I were you, I would rather make the first g element another svg element and add x and y attributes to it, like this:

var g1 = svg.append("svg")
    .attr("x", margin.left)
    .attr("y", margin.top)

And in the css, select the outer container by its class to change its outline:

.outline .svg-frame {
  outline: 1px solid red;
}

To get make an outline for the inner svg, I would add a rectangle to g1 after the container has been added:

g1.append("rect")
    .attr("width", innerWidth)
    .attr("height", innerHeight)
    .style("fill", "none")
    .style("stroke", "blue");

Upvotes: 2

Related Questions