Reputation: 630
I need to draw arrows between an element in svg1 and an element in svg2. Any idea how this can be done other than putting both svg elements into a single svg?
Upvotes: 1
Views: 82
Reputation: 7536
you can use a third svg that sits on top of both other svgs.
Position it, so the edges of the third svg sit exactly where you want your arrows to point, and use percentages for the lines x1,y1,x2,y2 coordiantes so it sits at 0%,0%,100%,100%.
don't forget to set pointer-events to none to still be able to interact with the page...
var c1 = document.getElementById("svg1").getBoundingClientRect()
var c2 = document.getElementById("svg2").getBoundingClientRect()
var svg3 = document.getElementById("svg3")
svg3.style.top = c1.top + c1.height / 2
svg3.style.left = c1.left + c1.width / 2
svg3.setAttribute("width", (c2.left + c2.width / 2) - (c1.left + c1.width / 2))
svg3.setAttribute("height", (c2.top + c2.height / 2) - (c1.top + c1.height / 2))
#svg3 {
position: absolute;
overflow: visible;
pointer-events: none;
}
#svg3 line {
marker-start: url(#arrowStart);
marker-end: url(#arrowEnd);
stroke-linecap: butt;
stroke: blue;
opacity: 0.5;
stroke-width: 5;
}
<svg id="svg1" width="100px" height="100px">
<circle cx="50" cy="50" r="40" fill="red" />
<circle cx="50" cy="50" r="5" fill="white" />
</svg>
some text...
<br/>some other text
<svg id="svg2" width="100px" height="100px">
<circle cx="50" cy="50" r="40" fill="green" />
<circle cx="50" cy="50" r="5" fill="white" />
</svg>
<svg id="svg3">
<marker id="arrowStart" viewBox="0 0 10 10" markerWidth="5" markerHeight="5" refX="8" refY="5" orient="auto-start-reverse">
<polygon points="0,0,10,5,0,10" stroke="none" />
</marker>
<marker id="arrowEnd" viewBox="0 0 10 10" markerWidth="5" markerHeight="5" refX="8" refY="5" orient="auto">
<polygon points="0,0,10,5,0,10" stroke="none" />
</marker>
<line x1="0%" y1="0%" x2="100%" y2="100%" />
</svg>
Upvotes: 4