Как мне разместить текст поверх круга?

#javascript #d3.js #svg

#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: absolute вместе с top и left , и он остается в том же углу.

Ответ №1:

В D3 attr методы используют Element.setAttribute внутренне, в то время как style использует CSSStyleDeclaration.setProperty() .

В <text> элементе SVG x и y являются атрибутами. Поэтому измените эти 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-anchor и dominant-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>  

Комментарии:

1. В чем разница между атрибутом и стилем? Мой ответ новичка заключается в том, что стиль относится к CSS, а атрибуты — к HTML.

2. @Cauder это немного сложнее, чем это. Я добавил первый абзац с некоторыми ссылками, пожалуйста, взгляните.