简体   繁体   English

如何使用d3.js在svg图像上居中显示文本?

[英]How to center a text on a svg image using d3.js?

I am trying to put a text so that it is located in the center of my element as in the following image: 我正在尝试放置一个文本,使其位于元素的中心,如下图所示: 在此处输入图片说明

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 http://plnkr.co/edit/39zEvnjOmotZXYF2GFwq?p=preview

You can simply put the image and text in a group container and adjust the text position relatively as shown below. 您可以简单地将图像和文本放在组容器中,并相对地调整文本位置,如下所示。

Plunker 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM