I have an SVG line & it gets moved around via js & I want to place some text along it, like this:

and every time the line moves the text should automatically move along with it while always staying in the center of the line no matter what the length
I tried a naive approach like this but it obviously didn't work:
<svg height="210" width="500">
<line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2">
Hello there
</line>
</svg>
is such a thing possible or will I have program the text to move as well in javascript?
every time the line moves the text should automatically move along with it
I think the most straightforward way to go about this would be to:
<line> and the <text> together using a <g>; and then<g> element with your javascript.N.B. I've used a CSS animation rather than javascript in the example below but the principle holds.
Working Example:
svg {
width: 500px;
height: 210px;
}
g {
transform-origin: 100%;
animation: rotateGroup 3s linear infinite;
}
line {
stroke: rgb(255,0,0);
stroke-width: 4px;
}
text {
fill: rgb(255, 0, 0);
font-size: 36px;
}
@keyframes rotateGroup {
0% {transform: rotate(0deg);}
100% {transform: rotate(360deg);}
}
<svg viewBox="0 0 105 250">
<g>
<line x1="0" y1="185" x2="200" y2="185" />
<text x="22" y="176">Hello there</text>
</g>
</svg>
Additional Note:
You mentioned:
while always staying in the center of the line no matter what the length
To achieve this you can recalculate the x value of <text> every time you recalculate the x1 and x2 values of <line>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With