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

376
Visualizações
Cómo calcular los valores exactos de trazo-raya para una animación perfecta

Estoy tratando de animate la propiedad stroke-dashoffset de un elemento svg de la siguiente manera

 const svg = document.querySelector("svg"); //const svgns = "http://www.w3.org/2000/svg" var ln = document.querySelector('.ln'); var path = ln.getTotalLength(); ln.style.setProperty("--off", path + 'px'); svg.appendChild(ln);
 .ln { stroke-dashoffset: var(--off); stroke-dasharray: 13; animation: effect 4s linear infinite; } @keyframes effect { 100% { stroke-dashoffset: 0px; } }
 <!DOCTYPE html> <html> <body> <link rel="stylesheet" href="style.css"></link> <svg id="layer" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500"> <rect class="boundary" x="100" y="100" height="100" width="130" fill="none" stroke="blue"></rect> <line class="ln" x1="100" y1="150" x2="230" y2="150" stroke = "grey" stroke-width="2" /> <script href="index.js"></script> </svg> </body> </html>

Una parte importante de esta animación es el valor stroke-dasharray .

Me he dado cuenta de que, según el valor de ese campo, la animación puede sentirse perfecta o no perfecta.

Por ejemplo, con valores como 5 and 13 , la animación se siente fluida. Para cualquier otro valor, la animación salta.

Además, me he dado cuenta de que 5 y 13 respectivamente producen

S1 S2

donde los guiones comienzan exactamente desde la izquierda y no tienen ningún residuo a diferencia de lo que stroke-dasharray =6, 10

S3 S4

¿Cómo puedo calcular los valores exact and safest stroke-dasharray para diferentes longitudes de path que harán que las líneas comiencen exactamente desde la izquierda sin residuos que produzcan la sensación perfecta en lugar de encontrarla a través de un sinfín de pruebas y errores?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Me he dado cuenta de esto.

Supongamos que la path length=120px y el stroke-dasharray=10px .

El stroke-dasharray=10 crea un guión de 10 píxeles de 10px wide dash + 10px wide gap de 10 píxeles de ancho como este

S1

Si la total path length divided by each (dash+gap) (20px en este caso) returns 0 ; eso significa que todos los elementos (120 px/cada stoke-dasharray de 10px * 2 [guión + espacio]) = 6 conjuntos (6 guiones + 6 espacios) pueden encajar perfectamente. Si la división devuelve el resto, entonces ese valor dash array no lo hará dan como resultado un ajuste perfecto de los elementos.

Con este conocimiento, la lógica se puede pasar a js para mover los hilos.

 const svg = document.querySelector("svg"); const svgns = "http://www.w3.org/2000/svg"; var x = 100; var y = 100; var height = 100; var width = 120; var midHeight = height / 2; let boundary = document.createElementNS(svgns, 'rect'); boundary.setAttribute("x", x); boundary.setAttribute("y", y); boundary.setAttribute("height", height); boundary.setAttribute("width", width); boundary.setAttribute("fill", "none"); boundary.setAttribute("stroke", "blue"); svg.appendChild(boundary); let line = document.createElementNS(svgns, 'line'); line.setAttribute("class", "ln") line.setAttribute("x1", x); line.setAttribute("x2", x + width); line.setAttribute("y1", x + midHeight); line.setAttribute("y2", x + midHeight); line.setAttribute("stroke", "grey"); line.setAttribute("stroke-width", "2"); svg.appendChild(line); var ln = document.querySelector('.ln'); var path = ln.getTotalLength(); var halfPath = path / 2; var possibleNumbers = []; for (var i = 0; i < halfPath; i++) { (halfPath % i) == 0 && (i != 1) ? possibleNumbers.push(i) : 0 }; ln.style.setProperty("--off", path + 'px'); ln.style.setProperty("--arr", possibleNumbers[5] + 'px'); svg.appendChild(ln);
 .ln { stroke-dashoffset: var(--off); stroke-dasharray: var(--arr); animation: effect 1s linear infinite; } @keyframes effect { 100% { stroke-dashoffset: 0px; } }
 <!DOCTYPE html> <html> <body> <link rel="stylesheet" href="style.css"></link> <svg id="layer" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500"> <script href="index.js"></script> </svg> </body> </html>

about 4 years ago · Juan Pablo Isaza 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