Bouncing box animation

This commit is contained in:
Ruben 2017-12-15 16:52:36 +01:00
parent c46c7f0e59
commit c5bf0f1a15

View file

@ -10,14 +10,77 @@
#viewbox{ #viewbox{
background:white; background:white;
position:absolute; position:absolute;
top:0; width: 17vw;
left:0; height: 17vw;
width:50%; }
height:100%;
.visible #viewbox{
top: 0 !important;
left: 0 !important;
width: 100% !important;
height: 100% !important;
} }
</style> </style>
<body> <body class=''>
<div id='viewbox'> <div id='viewbox'>
</div> </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> </body>
</html> </html>