0

I am trying to put a text so that it is located in the center of my element as in the following image: enter image description here

I would like this to be done dynamically depending on the size of my image.

How can I do it?

  <body>
  <script type="text/javascript">
    const svg = d3.select("body").append("svg").attr("width",1000).attr("height",1000);
    var widthMarker=50;
    var img = svg.append("svg:image")
        .attr("xlink:href", "marker.svg")
        .attr("width", widthMarker)
        .attr("height", widthMarker)
        .attr("x", 228)
        .attr("y",53);

        svg.append("text").attr("width",100).attr("height",100).text("hello world");



  </script>
  </body>

http://plnkr.co/edit/39zEvnjOmotZXYF2GFwq?p=preview

yavg
  • 2,761
  • 7
  • 45
  • 115
  • did you see this ? https://stackoverflow.com/questions/36268318/how-to-align-text-inside-svg-in-d3-js. you can try tspan, text-anchor middle – Jahangir Alam Mar 28 '18 at 02:48

1 Answers1

1

You can simply put the image and text in a group container and adjust the text position relatively as shown below.

Plunker

const svg = d3.select("body")
  .append("svg")
  .attr("width", 1000)
  .attr("height", 1000);

var widthMarker = 50;

var imgContainer = svg.append("g")
  .attr("transform", "translate(228,53)");

var img = imgContainer.append("svg:image")
  .attr("xlink:href", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQgfLDf_0gBVxWp_7ec2UR3Dro5rBXquElgRdSH6K8LQQ7QanSQ")
  .attr("width", widthMarker)
  .attr("height", widthMarker);

var text = imgContainer.append("svg:text")
  .attr("dy", widthMarker/2)
  .text("hello world");

text.attr("dx", (widthMarker - text.node().getComputedTextLength()) / 2);
<script src="https://d3js.org/d3.v3.min.js"></script>
Gilsha
  • 14,431
  • 3
  • 32
  • 47
  • it's great! Thank you very much, just one question, how can I detect if the text is off the scoreboard? in this case it is exited because it is a long text. – yavg Mar 28 '18 at 19:49
  • If `(widthMarker - text.node().getComputedTextLength())` is negative the text is wider than the marker. check the last line of code. – Gilsha Mar 29 '18 at 04:15