Created
April 16, 2019 13:07
-
-
Save DevShahidul/2e0fc87d91e41cc388f946ea407c83b2 to your computer and use it in GitHub Desktop.
See the example here >>> https://codepen.io/redspiderfish/pen/MYmeYz
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0, user-scalable=no"> | |
<meta name="format-detection" content="telephone=no"> | |
<title>Follow Mouse</title> | |
<style> | |
body { background-color:#000; heigt: 2400px;} | |
.left { | |
-moz-transform: scaleX(-1); | |
-o-transform: scaleX(-1); | |
-webkit-transform: scaleX(-1); | |
transform: scaleX(-1); | |
filter: FlipH; | |
-ms-filter: "FlipH"; | |
} | |
.right { | |
-moz-transform: scaleX(1); | |
-o-transform: scaleX(1); | |
-webkit-transform: scaleX(1); | |
transform: scaleX(1); | |
filter: FlipH; | |
-ms-filter: "FlipH"; | |
} | |
#bee {transition: transform .1s} | |
</style> | |
</head> | |
<body> | |
<div id="bee"> | |
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/160783/astroboy.png" /> | |
</div> | |
<script type="text/javascript"> | |
// Image follow mouse function | |
var bee = document.getElementById("bee"); | |
document.addEventListener("mousemove", getMouse); | |
bee.style.position = "absolute"; //css | |
var beepos = { | |
x: 0, | |
y: 0 | |
}; | |
setInterval(followMouse, 50); | |
var mouse = { | |
x: 0, | |
y: 0 | |
}; //mouse.x, mouse.y | |
var dir = "right"; | |
function getMouse(e){ | |
mouse.x = e.pageX; | |
mouse.y = e.pageY; | |
//Checking directional change | |
if (mouse.x > beepos.x) { | |
dir = "right"; | |
} else { | |
dir = "left"; | |
} | |
} | |
function followMouse(){ | |
//1. find distance X , distance Y | |
var distX = mouse.x - beepos.x; | |
var distY = mouse.y - beepos.y; | |
//Easing motion | |
//Progressive reduction of distance | |
beepos.x += distX / 5; | |
beepos.y += distY / 2; | |
bee.style.left = beepos.x + "px"; | |
bee.style.top = beepos.y + "px"; | |
//Apply css class | |
if (dir == "right") { | |
bee.setAttribute("class", "right"); | |
} else { | |
bee.setAttribute("class", "left"); | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment