mouse-stalker
by miyabi_irokoto
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.10.4/gsap.min.js"></script>
<!DOCTYPE html>
<html lang="ja"></html>
<head>
<meta charset="UTF-8"/>
<title></title>
<link rel="stylesheet" href="./assets/css/style.css"/>
</head>
<body>
<div class="container">
<div class="stalker"></div>
</div>
</body>
SCSS
body {
margin: 0;
}
.container{
width: 100vw;
height: 100vh;
position: relative;
background: #f7f7f7;
}
.stalker{
width: 20px;
height: 20px;
margin: auto;
position: absolute;
top: 0;
left: 0;
background: #000;
border-radius: 50%;
}
JavaScript
class stalker {
constructor(target){
this.gbcr = target.getBoundingClientRect();
this.el = {
target: target,
x: this.gbcr.x,
y: this.gbcr.y,
w: this.gbcr.width,
h: this.gbcr.height,
}
this.mouse = {
x: 0,
y: 0,
cx: 0,
cy: 0
}
window.addEventListener('mousemove', this.mouseMove.bind(this));
this.onRequestAnimationFrame();
}
mouseMove(e) {
this.mouse.x = e.clientX - (this.el.w / 2);
this.mouse.y = e.clientY - (this.el.h / 2);
}
onRequestAnimationFrame() {
this.mouse.cx = gsap.utils.interpolate(this.mouse.cx, this.mouse.x, 0.1);
this.mouse.cy = gsap.utils.interpolate(this.mouse.cy, this.mouse.y, 0.1);
gsap.set(this.el.target, {
x: this.mouse.cx,
y: this.mouse.cy
});
requestAnimationFrame(() => { this.onRequestAnimationFrame() });
}
}
new stalker(document.querySelector('.stalker'));