سؤال

So I'm working on a bubble graph in D3.js: http://bl.ocks.org/mbostock/4063269. The width and height are determined by the diameter. So I ask: how to make this SVG bubble cloud, and any other SVG responsive with as little re coding as possible?

<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>
هل كانت مفيدة؟

المحلول

Here is a FIDDLE with Mike's example you mentioned.

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

Essentially, you use the viewBox and preserveAspectRatio attributes on the svg and re-size accordingly.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top