This is a snippet from a notebook. Here, I’m splitting a string at \n
and inserting each using <tspan>
within <text>
.
I need to use this functionality in more than one places. What is a good way that I can write a function and use it in many places? I tried using selection.call
, but I didn’t find a good way to access the data from the parent <text>
.
const text = `A world of dew,
And within every dewdrop
A world of struggle.
—Kobayashi Issa`;
const lines = text.split("\n");
const textContentHeight = (lines.length - 1) * lineHeight * fontSize;
svg
.append("text")
// 👋 Is it possible to create re-usable function to do this function using selection.call(),
// selection.each()?
// .data(text)
// .call(multilineText, {fontFamily, fontFamily, textAnchor})
.attr("font-family", fontFamily)
.attr("font-size", fontSize)
.attr("dominant-baseline", "middle")
.attr("text-anchor", textAnchor)
.selectAll("tspan")
.data(lines)
.join("tspan")
.text((d) => d)
.attr("x", anchor.x)
.attr(
"y",
(d, i) => anchor.y + i * lineHeight * fontSize - textContentHeight / 2
);