Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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>.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!