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

193
Views
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 answers
Answer question

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