Last active
August 6, 2018 07:35
-
-
Save dethbiscuit/0ded2bdeb0e1d0d6dcb72ab3e8119166 to your computer and use it in GitHub Desktop.
[velocity] dragging animation
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
body { background-color:#20262E; } | |
#card { | |
position: absolute; | |
width: 250px; | |
height: 50px; | |
background: grey; | |
border-radius: 6px; | |
cursor: move; | |
} | |
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
<!-- SOURCE : https://uxdesign.cc/how-to-fix-dragging-animation-in-ui-with-simple-math-4bbc10deccf7 --> | |
<div id="card"></div> | |
<!-- temporary --> | |
<h3> 1.3m/s </h3> | |
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
/****************************************************************************************************** | |
--- SOURCE : https://uxdesign.cc/how-to-fix-dragging-animation-in-ui-with-simple-math-4bbc10deccf7 --- | |
******************************************************************************************************/ | |
// Temporary, for showing velocity at the top left. | |
var xVelocityDisplay = document.querySelector('h3'); | |
var updateVelocityDisplay = function(velocity) { | |
xVelocityDisplay.innerHTML = 'x velocity = ' + velocity + ' pixels/60frames'; | |
}; | |
var card = document.querySelector('#card'); | |
// Stores X and Y coordinates of Mouse | |
var MousePosition = { | |
x: 0, | |
y: 0 | |
}; | |
// Stores X and Y Coordinates of the Card | |
var CardPosition = { | |
x: 0, | |
y: 0 | |
}; | |
var xVelocity = 0; | |
// Temporary, for updating velocity at the top left. | |
setInterval(function() { | |
updateVelocityDisplay(xVelocity); | |
}, 100); | |
var update = function() { | |
xVelocity = (MousePosition.x - CardPosition.x); | |
CardPosition.x = MousePosition.x; | |
CardPosition.y = MousePosition.y; | |
// Update the position of card | |
card.style.top = CardPosition.y + 'px'; | |
// Subtract (Width of card / 2 = 125) to centre cursor on top | |
card.style.left = (CardPosition.x - 125) + 'px'; | |
requestAnimationFrame(update); | |
}; | |
update(); | |
document.addEventListener('mousemove', function(e) { | |
MousePosition.x = e.clientX; | |
MousePosition.y = e.clientY; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment