使SVG容器在D3 V4中的父容器的宽度和高度(而不是由像素)

  • 本文关键字:高度 像素 D3 SVG V4 d3.js
  • 更新时间 :
  • 英文 :


i有一个父容器(div.barchartcontainer(,其高度和宽度是根据视口计算的,例如:ex:width:calc(100vh -200px(。SVG容器附加到Div.BarchartContainer元素。

我正在努力如何使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 + ")");

解决方案是评论/删除宽度和高度属性值,而是添加以下两行:

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

检查SVG是用父高和宽度绘制的。

参考:https://bl.ocks.org/curran/3a68b0c81991e2e2e94b19

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>

最新更新