How can I achieve a dynamic SVG path between my word DIVs? This is my current progress and this is my desired outcome.
Could you please explain why my code isn't working as expected? I attempted to calculate the XY positions of my words to create an SVG path based on their start and end points.
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>SVG Path Animation</title>
</head>
<body>
<div id="container">
<div class="word" id="w1" style="margin-left: 10%; margin-top: 1%;">First</div>
<div class="word" id="w2" style="margin-left: 60%; margin-top: 2%;">Second</div>
<div class="word" id="w3" style="margin-left: 20%; margin-top: 3%;">Third</div>
<div class="word" id="w4" style="margin-left: 70%; margin-top: 4%;">Fourth</div>
<div class="word" id="w5" style="margin-left: 30%; margin-top: 5%;">Fifth</div>
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript :
document.addEventListener("DOMContentLoaded", function() {
const wa = document.getElementById("w1");
const wb = document.getElementById("w2");
const wc = document.getElementById("w3");
const wd = document.getElementById("w4");
const we = document.getElementById("w5");
const svgPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
const x1 = wa.offsetLeft + wa.offsetWidth;
const y1 = wa.offsetTop + wa.offsetHeight / 2;
const x2 = wb.offsetLeft;
const y2 = wb.offsetTop + wb.offsetHeight / 2;
const x3 = wc.offsetLeft + wc.offsetWidth;
const y3 = wc.offsetTop + wc.offsetHeight / 2;
const x4 = wd.offsetLeft;
const y4 = wd.offsetTop + wd.offsetHeight / 2;
const x5 = we.offsetLeft + we.offsetWidth;
const y5 = we.offsetTop + we.offsetHeight / 2;
// svgPath.setAttribute("d", M${x1},${y1} L${x2},${y2});
svgPath.setAttribute("d", `M ${x1},${y1} L ${x2},${y2} ${x3},${y3} ${x4},${y4} ${x5},${y5}`);
svgPath.setAttribute("stroke", "black");
svgPath.setAttribute("stroke-width", "2");
svgPath.setAttribute("fill", "none");
document.body.appendChild(svgPath);
});
CSS :
.word {
position: absolute;
font-size: 16px;
}
#container {
width: 1500px;
height: 900px;
position: relative;
}