Skip to content

Instantly share code, notes, and snippets.

@schollz
Created March 28, 2024 21:39
Show Gist options
  • Save schollz/4d19e286d73bb8551889b66abc39e7bc to your computer and use it in GitHub Desktop.
Save schollz/4d19e286d73bb8551889b66abc39e7bc to your computer and use it in GitHub Desktop.
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<span class="ant"></span>
<style>
.ant {
position:absolute;
background-image:url("https://ianparberry.files.wordpress.com/2013/02/antwalk.gif");
background-size: cover;
}
</style>
<script>
var mouseCoords = {x:1,y:1}; // current mouse position
var antSpeed = 100; // ant speed in pixels per second
var antSize = 30; // ant size in pixels
var lastUpdate = 0; // time of last animation update
var body = document.getElementsByTagName('body')[0];
var ants = document.getElementsByClassName('ant'); // get ant elements
// random position each ant and set size
for (var i = 0; i < ants.length; i++) {
randomPositionAnt(ants[i]);
ants[i].style.height = antSize + "px";
ants[i].style.width = antSize + "px";
}
// randomly position ant at edge of screen
function randomPositionAnt(ant) {
if (Math.random() < 0.5) {
ant.xLoc = 0;
} else {
ant.xLoc = body.clientWidth;
}
ant.yLoc = Math.random() * body.clientHeight;
};
// return true if distance between ant and cursor is less than 10 pixels
function isAntTouchingCursor(ant) {
return Math.sqrt((ant.xLoc - mouseCoords.x) * (ant.xLoc - mouseCoords.x) + (ant.yLoc - mouseCoords.y) * (ant.yLoc - mouseCoords.y)) < 10;
}
// set up mouse cursor listening
window.addEventListener('mousemove', function(data){
mouseCoords.x = data.clientX;
mouseCoords.y = data.clientY;
});
// function to call each animation cycle
function update() {
requestAnimationFrame(update);
var updateTime = new Date().getTime();
var timeDiff = (Math.min(100, Math.max(updateTime - lastUpdate, 0))) / 1000;
lastUpdate = updateTime;
for (var i = 0; i < ants.length; i++) {
var ant = ants[i];
var xDiff = mouseCoords.x - ant.xLoc;
var yDiff = mouseCoords.y - ant.yLoc;
var multi = Math.sqrt(Math.pow(xDiff, 2) + Math.pow(yDiff, 2));
var xSpeed = xDiff / multi * antSpeed;
var ySpeed = yDiff / multi * antSpeed;
var rotation = (180 * Math.atan2(yDiff, xDiff) / Math.PI) - 180;
ant.xLoc += xSpeed * timeDiff;
ant.yLoc += ySpeed * timeDiff;
if (isAntTouchingCursor(ant)) {
randomPositionAnt(ant);
}
ant.style.left = (ant.xLoc - (antSize / 2)) + "px";
ant.style.top = (ant.yLoc - (antSize / 2)) + "px";
ant.style.transform = "rotate(" + rotation + "deg)";
};
}
update();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment