Last active
December 23, 2023 02:29
-
-
Save johnrees/4225e41289956fca9020a74b4dd4db06 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
document.addEventListener("DOMContentLoaded", function () { | |
const speed = 1; // Adjust for faster or slower movement | |
const container = document.createElement("div"); | |
container.style.position = "fixed"; | |
container.style.top = 0; | |
container.style.bottom = 0; | |
container.style.left = 0; | |
container.style.right = 0; | |
container.style.pointerEvents = "none"; | |
container.style.userSelect = "none"; | |
container.style.zIndex = 99999999; | |
container.style.overflow = "hidden"; | |
document.body.appendChild(container); | |
const img = document.createElement("img"); | |
img.id = "floatingImage"; | |
img.src = | |
"https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM2ZmNXp1cHJqZzJjdXd1OW9kZ2JxOGZ5MjZseDRhZDZrZ2tueGhzMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9cw/SU2VnCFHPlqGNzQoGs/giphy.gif"; | |
img.style.width = "100px"; | |
img.style.position = "absolute"; | |
container.appendChild(img); | |
let count = 0; | |
let spinSpeed = 0; | |
hitEdge(); | |
let deltaX = 1; // X direction | |
let deltaY = 1; // Y direction | |
function hitEdge() { | |
spinSpeed = (Math.random() > 0.3 ? -1 : 1) * spinSpeed + Math.max(Math.min(Math.random() * 3, 4), -4); | |
} | |
function animate() { | |
const currentX = img.offsetLeft; | |
const currentY = img.offsetTop; | |
img.style.transform = `rotate(${count+=spinSpeed}deg)` | |
let nextX = currentX + deltaX * speed; | |
let nextY = currentY + deltaY * speed; | |
// Reverse direction upon hitting the edge | |
if (nextX <= 0 || nextX + img.clientWidth >= window.innerWidth) { | |
// container.style.transform = `translate(50%, 50%) rotate(360 - ${Math.random() * 720})`; | |
deltaX = -deltaX; | |
hitEdge(); | |
} | |
if (nextY <= 0 || nextY + img.clientHeight >= window.innerHeight) { | |
// container.style.transform = `translate(50%, 50%) rotate(360 - ${Math.random() * 720})`; | |
deltaY = -deltaY; | |
hitEdge(); | |
} | |
// Apply the next position | |
img.style.left = currentX + deltaX * speed + "px"; | |
img.style.top = currentY + deltaY * speed + "px"; | |
// Use requestAnimationFrame for smooth and continuous animation | |
requestAnimationFrame(animate); | |
} | |
// Start the animation | |
animate(); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment