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

Member

by lottie , in category: Javascript , 5 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 5 months ago

@lottie 

To center a text on a SVG image using D3.js, you can set the text-anchor attribute of the text element to middle, and set the x and y attributes to half of the width and height of the SVG image respectively.


Here is an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Select the SVG element
var svg = d3.select("svg");

// Get the width and height of the SVG element
var svgWidth = +svg.attr("width");
var svgHeight = +svg.attr("height");

// Add a text element to the SVG
svg.append("text")
  .attr("x", svgWidth / 2)
  .attr("y", svgHeight / 2)
  .attr("text-anchor", "middle")
  .text("Centered Text");


This code will add a text element to the center of the SVG image with the text "Centered Text". Adjust the x and y attributes if you want to position the text in a different position within the SVG image.