Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda