Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG lines with text on top

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

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?

like image 383
cak3_lover Avatar asked Dec 07 '25 07:12

cak3_lover


1 Answers

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:

  • group the <line> and the <text> together using a <g>; and then
  • transition or animate the <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>.

like image 59
Rounin - Glory to UKRAINE Avatar answered Dec 08 '25 21:12

Rounin - Glory to UKRAINE