保持D3圆形包的纵横比 - 响应式设计

时间:2014-04-04 11:48:09

标签: javascript d3.js responsive-design circle-pack

所以我正在处理D3.js中的气泡图:http://bl.ocks.org/mbostock/4063269。宽度和高度由直径决定。所以我问:如何制作这个SVG泡泡云,以及任何其他SVG响应尽可能少的重新编码?

<script>
var diameter = 628,
    format = d3.format(",d"),
    color = d3.scale.ordinal()
        .range(["#FFFFFF", "#7ec0ee", "#0D2A46"]);

var bubble = d3.layout.pack()
    .sort(null)
    .size([diameter, diameter])
    .padding(1.5);

function addChart(file, target){

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
    .attr("class", "bubble");

d3.json(file, function(error, root) {
  var node = svg.selectAll(".node")
      .data(bubble.nodes(classes(root))
      .filter(function(d) { return !d.children; }))
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  node.append("title")
      .text(function(d) { return d.className + ": " + format(d.value); });

  node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d) { return color(d.packageName); });

  node.append("text")
      .attr("dy", ".3em")
      .style("text-anchor", "middle")

      .text(function(d) { return d.className.substring(0, d.r / 3); });
});
}
addChart("DataGreatEnglishWriters.json", "dv.foo");
addChart("Dubliner.json", "div.bar");
addChart("2LeftFeet.json", "div.head");
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: node.size});
  }

  recurse(null, root);
  return {children: classes};
}

d3.select(self.frameElement).style("height", diameter + "px");

</script>

1 个答案:

答案 0 :(得分:4)

这是你提到的Mike的例子FIDDLE

var chart = $(".bubble"),
    aspect = chart.width() / chart.height(),
    container = chart.parent();

$(window).on("resize", function() {
    var targetWidth = container.width();
    chart.attr("width", targetWidth);
    chart.attr("height", Math.round(targetWidth / aspect));
}).trigger("resize");

基本上,您使用viewBox上的preserveAspectRatiosvg属性并相应地重新调整大小。