title: How to center text in a rect element in d3?
body: <p>I have created a d3 visualization that takes an array of data, creats a rect for each data point, and then displays the text in the rect. However, I have only gotten the text to display inside of the rect by giving it coordinates. I am wondering how I would tell it to center itself in the rect element. Here is the code:</p>
  
  <pre><code>var elementTags = ["Google", "Amazon", "Wikipedia", "Yahoo!", "Messi", "Ronaldo", "One", "Two", "Three",
               "Monkey"];
  </code></pre>
  
  <p>The next part creates arrays I used to position the rects</p>
  
  <pre><code>            var xPosLoop = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3];
              var yPosLoop = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]
  </code></pre>
  
  <p>set their width and height</p>
  
  <pre><code>            var elementWidth = 210;
              var elementHeight = 60;
  </code></pre>
  
  <p>create the svg container and add rects</p>
  
  <pre><code>            var svgContainer = d3.select("body") //create container
                      .append("svg")
                      .attr("width", 1000)
                      .attr("height", 1000);
              var enterElements = svgContainer.selectAll("rect") //draw elements
                      .data(elementTags).enter().append("rect")
                      .attr("x", function(d, i){
                          return xPosLoop[i]*(elementWidth+25);
                      })
                      .attr("height", elementHeight)
                      .attr("y", function(d, i){
                          return yPosLoop[i]*(elementHeight+35);
                      })
                      .attr("width", elementWidth)
                      .attr("rx", 4)
                      .attr("fill", "steelblue")
                      .attr("stroke", "black")
                      .attr("stroke-width", 1);
              var addText = svgContainer.selectAll("text").data(elementTags).enter().append("text");
  </code></pre>
  
  <p>and here is where i tell the text where to display, it's also where I need help. I want the text to center itself in the rects automatically.</p>
  
  <pre><code>            var textElements = addText
                  .attr("x", function(d, i){
                      return ((xPosLoop[i]*(elementWidth+25) +elementWidth/2))
                  })
                  .attr("y", function(d, i){
                      return ((yPosLoop[i]*(elementHeight+35)) + elementHeight/2 + 3)
                  })
                  .attr("font-family", "Arial Black")
                  .attr("font-size", "20px")
                  .attr("fill", "white")
                  .text(function(d, i){return d;});
  </code></pre>