Created
November 30, 2016 14:03
-
-
Save wjx/48d8b72de0c2f24f7236a69fe70bec1e to your computer and use it in GitHub Desktop.
Implementing mouse trail using requestAnimationFrame for EloquentJavaScript Exercise 14.2
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
<!doctype html> | |
<style> | |
.trail { /* className for the trail elements */ | |
position: absolute; | |
height: 6px; width: 6px; | |
border-radius: 3px; | |
background: teal; | |
} | |
body { | |
height: 300px; | |
} | |
</style> | |
<body> | |
<script> | |
var pointerX, pointerY; | |
var lastX = null, lastY = null; | |
var dots = []; | |
for (var i = 0; i < 12; i++) { | |
var node = document.createElement("div"); | |
node.className = "trail"; | |
node.setAttribute("targetTime", i + 1); | |
document.body.appendChild(node); | |
dots.push(node); | |
} | |
var currentDot = 0; | |
addEventListener("mousemove", function(event) { | |
pointerX = event.pageX; | |
pointerY = event.pageY; | |
}); | |
var delta = 0, lastTime = null; | |
function animate(time) { | |
if (lastTime != null) | |
delta = time - lastTime; | |
lastTime = time; | |
dots.forEach(function(dot) { | |
var boundingObj = dot.getBoundingClientRect(); | |
var currentX = boundingObj.left + 3; | |
var currentY = boundingObj.top + 3; | |
if (Math.abs(currentX - pointerX) < 1 && Math.abs(currentY - pointerY) < 1) { | |
dot.style.left = pointerX - 3; | |
dot.style.top = pointerY - 3; | |
return; | |
} | |
var currentDistance = Math.sqrt((currentX - pointerX) * (currentX - pointerX) + | |
(currentY - pointerY) * (currentY - pointerY)); | |
if (pointerX != lastX || pointerY != lastY) { | |
//targetTime is in second | |
var v = currentDistance / (dot.getAttribute("targetTime") * 1000); | |
dot.setAttribute("velocity", v); | |
} | |
var step = dot.getAttribute("velocity") * delta; | |
//step * cos | |
var stepX = step * ((pointerX - currentX) / currentDistance); | |
dot.style.left = boundingObj.left + stepX + "px"; | |
//step * sin | |
var stepY = step * ((pointerY - currentY) / currentDistance); | |
dot.style.top = boundingObj.top + stepY + "px"; | |
}); | |
lastX = pointerX; | |
lastY = pointerY; | |
requestAnimationFrame(animate); | |
} | |
requestAnimationFrame(animate); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment