I have a path I've created in svgwrite and I want to have my text to be centered along that path.
It's confusing since the svgwrite API doesn't appear to offer any mechanism for doing so
This leverages two passthrough parameters of the TextPath
You need to set two parameters on the TextPath
constructor:
text_anchor="middle"
to say that the text should be centered over the anchor pointstartOffset="50%"
to use the halfway mark of the path as the text's anchor point. (Without this, it'll look like your text is still left-aligned and that the first half of it has been chopped off)Sample code:
# setup canvas
dwg = svgwrite.Drawing()
dwg.viewbox(0,0,200,100)
# Create some path. This bit really matter
x1 = 20
y1 = 50
r1 = 50
arc = math.sqrt(2*(r1**2))
path = dwg.path(
d=f"m {x1},{y1} " + # starting point
f"a{r1},{r1} 0 0 1 {arc},0 " + # first arc
f"a{r1},{r1} 0 0 0 {arc},0 ", # second arc
stroke="#DDD",
fill="none")
# Center your text along path
text = svgwrite.text.Text("") # The text path must go inside a text object. Parameter used here gets ignored
text.add(svgwrite.text.TextPath(path, text="soy sol sonatora", startOffset="50%", method="align", text_anchor="middle"))
# Draw path and text
dwg.add(path)
dwg.add(text)