svg:子元素改变其父(svg容器)的大小

时间:2013-12-02 00:30:31

标签: javascript css svg d3.js

请看下面的图片:

enter image description here

每当图表放大(d3js)时,svg容器就会变大。为什么子元素(svg:g)的大小变化会影响其父容器(svg)的大小?我该如何防止这种情况发生?

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

1 个答案:

答案 0 :(得分:3)

使用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