Simple Curved Text Within A Circle
Solution 1:
As the name implies, a <textPath>
must be used with a <path>
element. You cannot use it with a <circle>
. If you look at the SVG specifications:
In addition to text drawn in a straight line, SVG also includes the ability to place text along the shape of a ‘path’ element. To specify that a block of text is to be rendered along the shape of a ‘path’, include the given text within a ‘textPath’ element which includes an ‘xlink:href’ attribute with an IRI reference to a ‘path’ element.
Therefore, you have to create paths. You can convert your circles to paths dealing with the d
attribute. For instance, supposing your cx = 100
, cy = 100
and r = 30
, this would be the d
attribute:
d = "M70,100 a 30,30 0 1,0 60,0 a 30,30 0 1,0 -60,0";
There are several online resources explaining how do you calculate the d
attribute based on cx
, cy
and r
, like this one.
Here is a demo:
const svg = d3.select("svg");
const circle = svg.append("path")
.style("fill", "none")
.style("stroke", "black")
.attr("d", "M70,100 a 30,30 0 1,0 60,0 a 30,30 0 1,0 -60,0");
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><svg></svg>
Now you can append the <textPath>
:
const svg = d3.select("svg");
const circle = svg.append("path")
.style("fill", "none")
.style("stroke", "black")
.attr("d", "M70,100 a 30,30 0 1,0 60,0 a 30,30 0 1,0 -60,0")
.attr("id", "myPath");
const textpath = svg.append("text")
.append("textPath")
.attr("xlink:href", "#myPath")
.text("Foo Bar Baz")
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><svg></svg>
Post a Comment for "Simple Curved Text Within A Circle"