Bouncing box animation

This commit is contained in:
Ruben 2017-12-15 16:52:36 +01:00
parent c46c7f0e59
commit c5bf0f1a15
1 changed files with 68 additions and 5 deletions

View File

@ -10,14 +10,77 @@
#viewbox{
background:white;
position:absolute;
top:0;
left:0;
width:50%;
height:100%;
width: 17vw;
height: 17vw;
}
.visible #viewbox{
top: 0 !important;
left: 0 !important;
width: 100% !important;
height: 100% !important;
}
</style>
<body>
<body class=''>
<div id='viewbox'>
</div>
<script type="text/javascript">
// speed per sec
var speedX = 10;
var speedY = 10;
var curX = 100;
var curY = 0;
var viewboxEl = document.getElementById("viewbox");
var lastTick = new Date();
function animate(){
let currentTime = new Date();
// time difference in ms
let timeDiff = currentTime - lastTick;
// strip the ms
timeDiff /= 1000;
// let secondsPassed = Math.round(timeDiff % 60);
let dX = speedX * timeDiff;
let dY = speedY * timeDiff;
curX += dX;
curY += dY;
let box = viewboxEl.getBoundingClientRect();
if(curX + box['width'] >= window.innerWidth){
speedX *= -1;
curX = window.innerWidth - box['width'];
} else if(curX <= 0) {
speedX *= -1;
curX = 0;
}
if(curY + box['height'] >= window.innerHeight){
speedY *= -1;
curY = window.innerHeight - box['height'];
} else if (curY <= 0) {
speedY *= -1;
curY = 0;
}
viewboxEl.style.left = curX + "px";
viewboxEl.style.top = curY + "px";
lastTick = currentTime;
window.requestAnimationFrame(animate);
}
window.addEventListener('load', function(){
animate();
});
</script>
</body>
</html>