在SVG的组元素之间给出间距并防止组重叠

时间:2017-06-12 12:23:41

标签: javascript d3.js svg

我有不同高度的组(svg组),我希望这些svg组彼此不重叠并且它们之间具有均匀的间距。 以下是我的jsfiddle的链接。 https://jsfiddle.net/3jxqgjcL/1/

var margin = { top: 10, right: 10, bottom: 30, left: 10 },
  width = 500 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom
distance = 0, barHeight = 75, i = 0;

function yAxis() {
  if (i == 0) {
    i++;
    return 2;
  } else {
    distance = parseInt(barHeight) * i;
    i++;
    return distance;
  }
}
var rectangles = d3.range(5).map(function() {
  return {
    x: 5,
    y: Math.round(yAxis())
  };
});

var color = d3.scaleOrdinal(d3.schemeCategory20);

var svg = d3.select("body").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 + ")")

var group = svg.selectAll('g')
  .data(rectangles)
  .enter().append("g")
  .attr("class", "groups")
  .attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")"
  })
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

group.append("rect")
  .attr("height", function(d,i){return Math.round(Math.random() * 100)})
  .attr("width", 360)
  .style("fill", function(d, i) {
    return color(i);
  });

var getheight = d3.select('g').node();
console.log("getheight"+ getheight.getBoundingClientRect().height);

group.append("text")
  .attr("text-anchor", "start")
  .style("fill", "steelblue")
  .text("Close");

function dragstarted(d) {
  d3.select(this).raise().classed("active", true);
}

function dragged(d) {
  d3.select(this).attr("transform", "translate(" + margin.left / 2 + "," + (d.y = d3.event.y) + ")");
}

function dragended(d) {
  d3.select(this).classed("active", false);
  var theseGroups = svg.selectAll(".groups").sort(function(a, b) {
    return d3.ascending(a.y, b.y);
  });
  theseGroups.attr("transform", function(d, i) {
    return "translate(" + margin.left / 2 + "," + (d.y = barHeight * i) + ")";
  })
}

0 个答案:

没有答案