A Pen by Anand prabhakar on CodePen.
Created
June 9, 2018 22:25
-
-
Save anandprabhakar0507/4fae76ce94e6cb17eb641981626ee6a6 to your computer and use it in GitHub Desktop.
JavaScript mouse trail
This file contains hidden or 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
// dots is an array of Dot objects, | |
// mouse is an object used to track the X and Y position | |
// of the mouse, set with a mousemove event listener below | |
var dots = [], | |
mouse = { | |
x: 0, | |
y: 0 | |
}; | |
// The Dot object used to scaffold the dots | |
var Dot = function() { | |
this.x = 0; | |
this.y = 0; | |
this.node = (function(){ | |
var n = document.createElement("div"); | |
n.className = "trail"; | |
document.body.appendChild(n); | |
return n; | |
}()); | |
}; | |
// The Dot.prototype.draw() method sets the position of | |
// the object's <div> node | |
Dot.prototype.draw = function() { | |
this.node.style.left = this.x + "px"; | |
this.node.style.top = this.y + "px"; | |
}; | |
// Creates the Dot objects, populates the dots array | |
for (var i = 0; i < 30; i++) { | |
var d = new Dot(); | |
dots.push(d); | |
} | |
// This is the screen redraw function | |
function draw() { | |
// Make sure the mouse position is set everytime | |
// draw() is called. | |
var x = mouse.x, | |
y = mouse.y; | |
// This loop is where all the 90s magic happens | |
dots.forEach(function(dot, index, dots) { | |
var nextDot = dots[index + 1] || dots[0]; | |
dot.x = x; | |
dot.y = y; | |
dot.draw(); | |
x += (nextDot.x - dot.x) * .6; | |
y += (nextDot.y - dot.y) * .6; | |
}); | |
} | |
addEventListener("mousemove", function(event) { | |
//event.preventDefault(); | |
mouse.x = event.pageX; | |
mouse.y = event.pageY; | |
}); | |
// animate() calls draw() then recursively calls itself | |
// everytime the screen repaints via requestAnimationFrame(). | |
function animate() { | |
draw(); | |
requestAnimationFrame(animate); | |
} | |
// And get it started by calling animate(). | |
animate(); |
This file contains hidden or 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
.trail { /* className for the trail elements */ | |
position: absolute; | |
height: 6px; width: 6px; | |
border-radius: 3px; | |
background: red; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment