Maximus S
Maximus S

Reputation: 11095

svg: child element alters its parent(svg container)'s size

Look at the picture below:

enter image description here

The svg container becomes larger whenever the chart is zoomed in (d3js). How come the child element(svg:g)'s change in size affects the size of its parent container(svg)? How do I prevent this from happening?

var svgContainer = d3.select(".graph-container").append("svg")
  .attr("id", "firstGraph")
  .attr("width", w + margin[2] + margin[3]) // labels are placed in the margins
  .attr("height", h + margin[0] + margin[1])
  //.attr("viewBox", "0 0 "+(w+margin[2]+margin[3])+" "+containerHeight)
  //.attr("preserveAspectRation", "xMidYMid")
  .attr("transform", "translate(" + margin[2] + "," + margin[0] + ")")
  //.append("svg:g")
  //.attr("transform", "translate(" + margin[2] + "," + margin[0] + ")"); //origin at (marginLeft, marginTop)

var graph = svgContainer.append("svg:g")
  .attr("width", w)
  .attr("height", h)
  .call(zoom);

var rect = graph.append("svg:rect")
  .attr("width", w)
  .attr("height", h)
  .attr("class", "plot");

//draw price data line
graph.append("path")
  .attr("d", line1(priceData))
  .attr("class", "price");

//draw difficulty data line
graph.append("path")
  .attr("d", line2(difficultyData))
  .attr("class", "difficulty");

Upvotes: 1

Views: 756

Answers (1)

Adam Pearce
Adam Pearce

Reputation: 9293

Use a clipPath:

svgContainer.append("defs").append("clipPath")
    .attr("id", "clip")
  .append("rect")
    .attr("width", w)
    .attr("height", h);

...

graph.append("path")
  .attr("d", line1(priceData))
  .attr("clip-path", "url(#clip)")
  .attr("class", "price");

MDN on clipPaths

Upvotes: 4

Related Questions