Home > Net >  How to draw lines dynamically on SVG Picture?
How to draw lines dynamically on SVG Picture?

Time:07-29

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!

CodePudding user response:

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);
  }
});
  • Related