在响应式D3 SVG上将圆垂直居中

时间:2018-09-03 15:33:48

标签: javascript d3.js svg

我正在尝试在响应式svg上绘制一些圆圈。

这是svg的代码:

const width = window.innerWidth;
const circleWidth = width / 2;
let h = 700;

const svgBackground = d3.select("#container")
  .append("svg")
  .attr("viewBox", `0 0 ${width} ${h}`)
  .classed("svg-content", true)
  .on("mouseleave", function () {
    d3.selectAll("circle.neo")
        .style("stroke", ringColour);

    d3.select("div#container")
        .selectAll("p")
        .remove();
})

它可以响应缩放,但我不知道如何绘制圆圈,使它们垂直居中

let height = svgBackground.style("height");
height = height.slice(0, (height.length - 2));
const halfHeight = height / 2;

let circles = svgBackground.selectAll("circle.neo")
        .data(radius)
        .enter()
        .append("circle")
        .attr("class", "neo")

let circleAttributes = circles
        .attr("cx", circleWidth)
        .attr("cy", halfHeight)
        .attr("r", function (d) { return d })
        .style("stroke", ringColour)
        .style("fill", "none")

如果有人对如何操作有任何建议,我将不胜感激。这是js小提琴http://jsfiddle.net/ncbtdk8m/1/

的完整代码

2 个答案:

答案 0 :(得分:0)

我认为您的问题是SVG底部的一部分不可见,因为.svg-container具有overflow:hidden属性。这使它看起来好像不在中心。

如果您删除了该CSS属性并正确配置了身高,则情况看起来将有所不同:http://jsfiddle.net/9dprfwj1/

答案 1 :(得分:0)

部分问题是div#containersvg.svg-content的样式。

不需要使用positiondisplay属性。

您没有为svg设置widthheight,并且没有调整大小的处理程序,因此如何响应。

为什么每次使用滑块时都要添加一个新的中心圆。

您只能获得半径0.5的80颗星。