Search code examples
d3.jssvgtransformtranslate

How to transfrom/translate text element in d3?


I'm trying to translate my svg text (axis label) in order I can center it with svg container. I've tried with this code:

svg.append("text")
  .attr("x", 100)
  .attr("y",100)
  .attr("transform", "translate(-50%, -50%)")
  .text("any text");

Moreover nothing happens. Other svg elements are translated with no problems, but, The text doesn't move from its original position. What is wrong, whats is the correct way to translate svg text?


Solution

  • Remove the % signs from the arguments you pass to translate:

    svg.append("text")
      .attr("x", 100)
      .attr("y", 100)
      .attr("transform", "translate(-50, -50)")
      .text("any text");
    

    You can check the MDN docs.