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

202
Visualizações
How to draw lines dynamically on SVG Picture?

I'm trying to develop an Attack Map when basically like all maps it will show the "Attacks" that are happening over the world but basically it will be randomly as I don't have access to any AV's APIs to get correct data. As of now I only have this SVG map shown on my HTML page: enter image description here

And I'd want to draw some lines from one country to another to simulate the attacks. I have been searching about this and I have seen two "solutions". One is a JS code that draws a line in HTML:

    if (stroke){
        ctx.strokeStyle = stroke;
    }

    if (width){
        ctx.lineWidth = width;
    }

    ctx.beginPath();
    ctx.moveTo(...begin);
    ctx.lineTo(...end);
    ctx.stroke();

}

const canvas = document.querySelector("#line");
if(canvas.getContext){
    const ctx = canvas.getContext('2d');
    drawLine(ctx, [100, 100], [300, 100], 'green', 5)
}

but as I said this draws a line outside of the SVG map and inside of HTML. I also saw a line tag which can be placed inside of SVG tags but it is static. I want to be dynamic and simulate the attacks. Is there any way I can do this? Thank you for your time!

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Even if the SVG element is static, you can add <line /> elements dynamically when the DOM has loaded:

const lines = [
  {
    from: { x: 0, y: 20 },
    to: { x: 30, y: 60 }
  },
  {
    from: { x: 0, y: 20 },
    to: { x: 30, y: 60 }
  }
];

function addLine (x1, y1, x2, y2) {
  const line = document.createElementNS('http://www.w3.org/2000/svg','line');
  
  line.setAttribute("x1", x1);
  line.setAttribute("y1", y1);
  line.setAttribute("x2", x2);
  line.setAttribute("y2", y2);
  line.setAttribute("stroke", "white");
  
  document.getElementById("mySvg").appendChild(line);
}

addEventListener("DOMContentLoaded", function () {
  for (const line of lines) {
    addLine(line.from.x, line.from.y, line.to.x, line.to.y);
  }
});
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