2017-06-29 30 views
2

我有一個父容器(div.barChartContainer),它的高度和寬度都是從視口計算出來的,例如:width:calc(100vh - 200px)。 SVG容器被附加到div.barChartContainer元素。製作SVG容器在D3 v4中父容器的寬度和高度都是100%(而不是像素)

我正在努力如何讓SVG元素的寬度和高度達到其父元素的100%,希望我能得到一些幫助。現在我有靜態像素量(它目前呈現正確,但沒有響應)。

謝謝!

var margin = {top: 20, right: 20, bottom: 30, left: 80}, 
      width = 960 - margin.left - margin.right, 
      height = 500 - margin.top - margin.bottom;   
      // set the ranges 
      var y = d3.scaleBand() 
      .range([height, 0]) 
      .padding(0.4); 
      var x = d3.scaleLinear() 
      .range([0, width]);   
      var svg = d3.select(".barChartContainer").append("svg") 
      .attr("width", width + margin.left + margin.right) 
      .attr("height", height + margin.top + margin.bottom) 
      .append("g") 
      .attr("transform", 
      "translate(" + margin.left + "," + margin.top + ")"); 
+1

這是有用嗎? https://stackoverflow.com/questions/9400615/whats-the-best-way-to-make-a-d3-js-visualisation-layout-responsive – RobinL

+0

@RobinL - 是的,謝謝你! –

回答

2

的解決方案是註釋/刪除的寬度和高度屬性值,而是添加以下兩行:

//- .attr("width", width + margin.left + margin.right) 
//- .attr("height", height + margin.top + margin.bottom) 
.attr("preserveAspectRatio", "xMinYMin meet") 
.attr("viewBox", "0 0 960 500") 
0

檢查svg是用父級高度和寬度繪製的。

價:https://bl.ocks.org/curran/3a68b0c81991e2e94b19

var parentDiv = document.getElementById("parentDiv"); 
 
var svg = d3.select(parentDiv).append("svg"); 
 

 
function redraw(show) { 
 

 
    // Extract the width and height that was computed by CSS. 
 
    var width = parentDiv.clientWidth; 
 
    var height = parentDiv.clientHeight; 
 
    // Use the extracted size to set the size of an SVG element. 
 
    svg 
 
    .attr("width", width) 
 
    .attr("height", height); 
 
    if (show === false) { 
 
    svg.style('visibility', 'hidden'); 
 
    } else { 
 
    svg.style('visibility', 'visible'); 
 
    } 
 

 
    svg.attr("style", "outline: thin solid red;") 
 
    .append("circle") 
 
    .attr("cx", 30) 
 
    .attr("cy", 30) 
 
    .attr("r", 20); 
 
} 
 

 
// Draw for the first time to initialize. 
 
redraw(false); 
 

 
// Redraw after sometime 
 
setTimeout(redraw, 1000);
#parentDiv { 
 
    height: calc(100vh - 100px); /** output container is small for display */ 
 
    width: calc(100vw - 100px); 
 
    display: block; 
 
    border: 1px solid red; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.10/d3.min.js"></script> 
 
<div id="parentDiv"></div>

相關問題