Для "наглядия".
<!DOCTYPE html>
<style type = "text/css">
*{
margin: 0px;
padding: 0px;
}
html,body, .wrapper, #line{
height: 100%;
width: 100%;
}
.wrapper{
position: relative;
}
#line{
_border:1px solid red;
display: block;
}
.guilty{
position: absolute;
width: 100px;
height: 100px;
cursor: pointer;
}
#one{
background-color: red;
top:50px;
left:50px;
}
#two{
top: 100px;
left: 100px;
background-color: blue;
}
</style>
<div class = "wrapper">
<canvas id = "line"></canvas>
<div id = "one" class = "guilty"></div>
<div id = "two" class = "guilty"></div>
</div>
<script type = "text/javascript">
function getOffset(elem) {
if (elem.getBoundingClientRect) {
return getOffsetRect(elem);
} else {
return getOffsetSum(elem);
}
}
function getOffsetSum(elem) {
var top = 0, left = 0;
while(elem) {
top = top + parseInt(elem.offsetTop);
left = left + parseInt(elem.offsetLeft);
elem = elem.offsetParent;
}
return {
top: top,
left: left
}
}
function getOffsetRect(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return {
top: Math.round(top),
left: Math.round(left)
}
}
window.onload = function(){
var one = document.getElementById("one");
var two = document.getElementById("two");
var line = document.getElementById("line").getContext("2d");
function addDrag(e){
var target = e ? e.target : window.event.strElement;
function drag(event){
event || (event = window.event);
var html = document.documentElement, body = document.body;
if(event.pageX == null && event.clientX != null){
event.pageX = event.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0);
event.pageY = event.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0);
}
var oneOffset = getOffset(one);
var twoOffset = getOffset(two);
if(target === one){
one.style.left = event.pageX - 50 + "px";
one.style.top = event.pageY - 50 + "px";
}else if(target === two){
two.style.left = event.pageX - 50 + "px";
two.style.top = event.pageY - 50 + "px";
}
var w = html.clientWidth, h = html.clientHeight, cw = line.canvas.width, ch = line.canvas.height;
line.beginPath();
line.clearRect(0,0, cw, ch);
line.moveTo((oneOffset.left + 50)/w*cw, (oneOffset.top + 50)/h*ch);
line.lineTo((twoOffset.left + 50)/w*cw, (twoOffset.top + 50)/h*ch);
line.stroke();
line.closePath();
}
document.onmousemove = drag;
}
function removeDrag(){
this.onmousemove = null;
}
one.onmousedown = addDrag;
two.onmousedown = addDrag;
document.onmouseup = removeDrag;
}
</script>