I'm trying to connect two points with a line while moving one of them. I'm really lost in finding the real x, y position of anything on a document... I've read about how paddings, element sizes and all these things can mess up this process, but none of the tutorials or example codes worked. I would really appreciate if you could give my code a look and give a solution/url to some kind of tutorial or just a basic startingpoint. Thanks in advance!
var node = document.querySelector("#node");
var startNode = document.querySelector("#startnode");
var container = document.querySelector("#container");
container.addEventListener("click", SetNodePosition, false);
function SetNodePosition(e) {
startX = getPosition(startNode).x;
startY = getPosition(startNode).y;
nodeX = getPosition(node).x;
nodeY = getPosition(node).y;
console.log("StartNode: " + startX + " - " + startY);
console.log("Node: " + nodeX + " - " + nodeY)
var translate3dValue = "translate3d(" + nodeX + "px," + nodeY + "px, 0)";
node.style.transform = translate3dValue;
if(typeof(document.getElementById("line1")) != 'undefined' && document.getElementById("line1") != null){
updateLine(startX, nodeX, startY, nodeY, "line1");
}
else{
createLine(startX, nodeX, startY, nodeY, "line1");
}
}
function getPosition(element) {
//FIND AND RETURN ELEMENT X, Y POSITION
}
function createLine(x1, x2, y1, y2, lineId) {
distance = Math.sqrt(((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)));
xMid = (x1+x2)/2;
yMid = (y1+y2)/2;
slopeInRadian = Math.atan2(y1-y2, x1-x2);
slopeInDegrees = (slopeInRadian*180)/Math.PI;
var line = document.createElement("div");
line.setAttribute("id", lineId);
line.style.height = "2px"
line.style.backgroundColor = "black"
line.style.width = distance + "px";
line.style.top = yMid + "px";
line.style.left = (xMid - (distance/2)) + "px";
line.style.transform = "rotate(" + slopeInDegrees + "deg)";
document.getElementById("container").appendChild(line);
console.log()
}
function updateLine(x1, x2, y1, y2, lineId) {
distance = Math.sqrt(((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)));
xMid = (x1+x2)/2;
yMid = (y1+y2)/2;
slopeInRadian = Math.atan2(y1-y2, x1-x2);
slopeInDegrees = (slopeInRadian*180)/Math.PI;
var line = document.getElementById(lineId)
line.style.width = distance + "px";
line.style.top = yMid + "px";
line.style.left = (xMid - (distance/2)) + "px";
line.style.transform = "rotate(" + slopeInDegrees + "deg)";
}
#container {
background-color: cornflowerblue;
height: 500px;
width: 500px;
}
#startnode {
height: 50px;
width: 50px;
background-color: green;
border-radius: 50%;
transform: translate3d(200px, 25px, 0);
}
#node {
height: 50px;
width: 50px;
cursor: move;
background-color: red;
border-radius: 50%;
transform: translate3d(50px, 50px, 0);
}
body {
padding: 0;
margin: 0;
}
<body>
<div id="container">
<div id="startnode"></div>
<div id="node"></div>
</div>
<script src="./js/index.js"></script>
</body>