JSFiddle - React, Tailwind, and code Playground
by velo_ninja
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bouncing Image</title>
<style>
body {
margin: 0;
overflow: hidden;
}
#bouncingImage {
width: 50px;
height: 50px;
position: absolute;
background: url('your-image.jpg') center/cover; /* Replace 'your-image.jpg' with your image file */
background-color: red; /* Add a background color for visibility */
}
</style>
</head>
<body>
<div id="bouncingImage"></div>
<script>
const bouncingImage = document.getElementById('bouncingImage');
let x = Math.random() * window.innerWidth;
let y = Math.random() * window.innerHeight;
let xSpeed = 5;
let ySpeed = 5;
function update() {
x += xSpeed;
y += ySpeed;
// Bounce off the right and left edges
if (x + bouncingImage.clientWidth > window.innerWidth || x < 0) {
xSpeed *= -1;
}
// Bounce off the bottom and top edges
if (y + bouncingImage.clientHeight > window.innerHeight || y < 0) {
ySpeed *= -1;
}
bouncingImage.style.left = `${x}px`;
bouncingImage.style.top = `${y}px`;
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>