如何在圆形上方放置文字?

时间:2019-03-15 07:36:48

标签: javascript d3.js svg

我有圈出代码,我想在其上方放置文字。

我将其用作示例:https://bl.ocks.org/mbostock/raw/7341714/

    infoHeight = 200
    infoWidth = 200

    var compareSVG = d3.select(".info-container")
                .append("svg")
                .attr("class","comparison-svg")
                .attr("width", infoWidth)
                .attr("height", infoHeight);

    var circle = compareSVG.append("g")

    circle.append("circle")
    .attr("r", circleRadius(d.properties.contextvalue))
    .attr("cy", infoHeight/2)
    .attr("cx", infoWidth/2)
    .style("fill","grey")
    .style("stroke","black")
    .style("stroke-width","3px")

    circle.append("text")
    .text(d.properties.contextvalue)
    .style("display", "block")
    .style("y", infoHeight/2)
    .style("x", infoHeight/2)
    .style("color","red")
    .style("font-size","20px")

该圆圈有效,但文本不会显示在其顶部。相反,它位于SVG元素的左上角。我已经尝试将position: absolutetopleft一起使用,并且它位于同一角落。

1 个答案:

答案 0 :(得分:1)

在D3中,attr方法在内部使用Element.setAttribute,而style在使用CSSStyleDeclaration.setProperty()

在SVG <text>元素中,xy属性。因此,将那些style()的方法更改为attr()。另外,请摆脱该.style("display", "block")

因此,应该是:

circle.append("text")
    .text(d.properties.contextvalue)
    .attr("y", infoHeight/2)
    .attr("x", infoHeight/2)
    .style("color","red")
    .style("font-size","20px")

这是您所做的更改的代码:

infoHeight = 200
infoWidth = 200

var compareSVG = d3.select("body")
  .append("svg")
  .attr("width", infoWidth)
  .attr("height", infoHeight);

var circle = compareSVG.append("g")

circle.append("circle")
  .attr("r", 50)
  .attr("cy", infoHeight / 2)
  .attr("cx", infoWidth / 2)
  .style("fill", "lightgrey")
  .style("stroke", "black")
  .style("stroke-width", "3px")

circle.append("text")
  .text("Foo Bar Baz")
  .attr("y", infoHeight / 2)
  .attr("x", infoHeight / 2)
  .style("color", "red")
  .style("font-size", "20px")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

最后,请注意文本的位置:未输入(相对于圆圈)。如果要居中,请使用text-anchordominant-baseline

infoHeight = 200
infoWidth = 200

var compareSVG = d3.select("body")
  .append("svg")
  .attr("width", infoWidth)
  .attr("height", infoHeight);

var circle = compareSVG.append("g")

circle.append("circle")
  .attr("r", 50)
  .attr("cy", infoHeight / 2)
  .attr("cx", infoWidth / 2)
  .style("fill", "lightgrey")
  .style("stroke", "black")
  .style("stroke-width", "3px")

circle.append("text")
  .text("Foo Bar Baz")
  .attr("y", infoHeight / 2)
  .attr("x", infoHeight / 2)
  .attr("text-anchor", "middle")
  .attr("dominant-baseline", "central")
  .style("color", "red")
  .style("font-size", "20px")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>