calc distance between two moving elements
by Flo Fromager
HTML
<div id="container">
<div id="hresult"></div>
<div id="vresult"></div>
<div id="x"></div>
<div id="y"></div>
</div>
CSS
html,
body {
margin: 0;
padding: 0;
font-family:monospace;
}
* {
transition: all 1s;
}
#x,
#y {
width: 50px;
height: 50px;
position:fixed;
left:0;
top:0;
background:black;
}
#container {
height: 100vh;
width: 100vw;
padding:10px;
background: lightgrey;
}
#x{
-webkit-animation: leftMove 10s infinite;
animation: leftMove 10s infinite;
top:calc(50vh - 25px);
}
@-webkit-keyframes leftMove {
0% {margin-left: 0;}
50% {margin-left: calc(100vw - 50px);}
100% {margin-left: 0;}
}
@keyframes leftMove {
0% {margin-left: 0;}
50% {margin-left: calc(100vw - 50px);}
100% {margin-left: 0;}
}
#y{
left:calc(50vw - 25px);
-webkit-animation: topMove 10s infinite;
animation: topMove 10s infinite;
}
@-webkit-keyframes topMove {
0% {margin-top: 0vh;}
50% {margin-top: calc(100vh - 50px);}
100% {margin-top: 0vh;}
}
@keyframes topMove {
0% {margin-top: 0vh;}
50% {margin-top: calc(100vh - 50px);}
100% {margin-top: 0vh;}
}
JavaScript
var $x = $('#x');
var $y = $('#y');
var $hresult = $('#hresult');
var $vresult = $('#vresult');
var $container = $('#container');
function updateDistance() {
var lFirst = $x.offset().left;
var lSecond = $y.offset().left;
var lDistP = parseInt(lFirst - lSecond);
var lDistN = parseInt(lSecond - lFirst);
var tFirst = $x.offset().top;
var tSecond = $y.offset().top;
var tDistP = parseInt(tFirst - tSecond);
var tDistN = parseInt(tSecond - tFirst);
// var totalDist = parseInt(tDist - (-lDist));
if(lFirst > lSecond){
$hresult.text('h:'+parseInt(lDistP));
if(tFirst > tSecond){
$vresult.text('v:'+parseInt(tDistP));
$x.css('background', 'rgb(' + (255 - (parseInt(lDistP + tDistP)/2)) + ',0,0)');
$y.css('background', 'rgb(' + (255 - (parseInt(lDistP + tDistP)/2)) + ',0,0)');
} else{
$vresult.text('v:'+parseInt(tDistN));
$x.css('background', 'rgb(' + (255 - (parseInt(lDistP + tDistN)/2)) + ',0,0)');
$y.css('background', 'rgb(' + (255 - (parseInt(lDistP + tDistN)/2)) + ',0,0)');
}
} else {
$hresult.text('h:'+parseInt(lDistN));
if(tFirst > tSecond){
$vresult.text('v:'+parseInt(tDistP));
$x.css('background', 'rgb(' + (255 - (parseInt(lDistN + tDistP)/2)) + ',0,0)');
$y.css('background', 'rgb(' + (255 - (parseInt(lDistN + tDistP)/2)) + ',0,0)');
} else{
$vresult.text('v:'+parseInt(tDistN));
$x.css('background', 'rgb(' + (255 - (parseInt(lDistN + tDistN)/2)) + ',0,0)');
$y.css('background', 'rgb(' + (255 - (parseInt(lDistN + tDistN)/2)) + ',0,0)');
}
}
//$result.text(lDist);
// if(lDist>=0){
// $result.text(parseInt(lDist));
// $container.css('background', 'rgb(255,255,' + (255 -(parseInt(lDist))*2) + ')');
//}else{
// $result.text(-parseInt(lDist));
// $container.css('background', 'rgb(255,255,' + (255 -(-parseInt(lDist))*2) + ')');
//}
}
setInterval(updateDistance, 100);