Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda