Skip to content

Instantly share code, notes, and snippets.

@hxtree
Created February 9, 2024 15:37
Show Gist options
  • Save hxtree/cd9f448d24d45d493e1ce4a269e37f08 to your computer and use it in GitHub Desktop.
Save hxtree/cd9f448d24d45d493e1ce4a269e37f08 to your computer and use it in GitHub Desktop.
getBoundingClientRect
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bouncing Boxes</title>
<style>
.box {
width: 50px;
height: 50px;
position: absolute;
}
#boxA {
background-color: blue;
top: 50px;
left: 50px;
}
#boxB {
background-color: green;
top: 150px;
left: 150px;
}
</style>
</head>
<body>
<div id="boxA" class="box"></div>
<div id="boxB" class="box"></div>
<script>
const boxA = document.getElementById('boxA');
const boxB = document.getElementById('boxB');
let dxA = 2; // Horizontal velocity of box A
let dyA = 2; // Vertical velocity of box A
let dxB = -2; // Horizontal velocity of box B
let dyB = -2; // Vertical velocity of box B
function moveBoxes() {
const rectA = boxA.getBoundingClientRect();
const rectB = boxB.getBoundingClientRect();
// Move box A
let newLeftA = rectA.left + dxA;
let newTopA = rectA.top + dyA;
// Check collision with window edges for box A
if (newLeftA < 0 || newLeftA + rectA.width > window.innerWidth) {
dxA = -dxA; // Reverse horizontal velocity
}
if (newTopA < 0 || newTopA + rectA.height > window.innerHeight) {
dyA = -dyA; // Reverse vertical velocity
}
// Move box B
let newLeftB = rectB.left + dxB;
let newTopB = rectB.top + dyB;
// Check collision with window edges for box B
if (newLeftB < 0 || newLeftB + rectB.width > window.innerWidth) {
dxB = -dxB; // Reverse horizontal velocity
}
if (newTopB < 0 || newTopB + rectB.height > window.innerHeight) {
dyB = -dyB; // Reverse vertical velocity
}
// Update box positions
boxA.style.left = newLeftA + 'px';
boxA.style.top = newTopA + 'px';
boxB.style.left = newLeftB + 'px';
boxB.style.top = newTopB + 'px';
// Check if Box B is below Box A
if (newTopB > newTopA) {
boxB.style.backgroundColor = 'red';
} else {
boxB.style.backgroundColor = 'green';
}
}
setInterval(moveBoxes, 10); // Move boxes every 10 milliseconds
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment