0
1

【JavaScript】特定のコンテナーの中だけマウスストーカーを出現させたい

Last updated at Posted at 2023-12-18

はじめに

ページ全体に反映させるのではなく、特定の範囲内だけポインターデザインを変える方法を調べていました。今回はGSAPを使用し、マウスストーカーを作成しています。

問題

■ カーソル位置がズレる

.containerを基準に位置を取得するため、offsetXやoffsetYを使用したのですが……カーソルが範囲外に出るとマウスストーカーがあらぬ方向に吹っ飛び、思うように追従してくれません。

index.html
<div class="wrapper">
    <div id="container" class="container">
     <!-- この中でのみマウスストーカーを動かしたい -->
		<div id="follower" class="follower"></div>
	</div>
</div>
style.css
.wrapper {
	width: 100vw;
	height: 100vh;
	display: flex;
	justify-content: center;
	align-items: center;
}

.contaier{
	width: 400px;
	height: 400px;
}

.follower {
	height: 20px;
	width: 20px;
	border-radius: 50%;
	z-index: 100;
 	/* background: 任意の色; */
 }
script.js
const el = document,
    follower = el.getElementById("follower"),
    pos = { x: 0, y: 0 };

// チラつき防止
let followerX = gsap.quickTo(follower, "x", { duration: 0.9 }),
    followerY = gsap.quickTo(follower, "y", { duration: 0.9 });

// 座標の取得
window.addEventListener("mousemove", (e) => {
    pos.x = e.offsetX;
	pos.y = e.offsetY;
});

gsap.ticker.add(function () {
	followerX(pos.x);
	followerY(pos.y);
});

解決方法

■ offsetの基準位置が変わっていた

とても分かりやすい例がこちらの記事にありました。
カーソルが.container外にでたとき、カーソルの座標は.wrapperの左上を基準にした値になっていたのでした。

script.js
const container = el.getElementById("container");

container.addEventListener("mousemove", (e) => {
    pos.x = e.offsetX;
	pos.y = e.offsetY;
});

おわりに

そもそも実用的なシチュエーションがあるのかは不明なのですが、勉強になったのでまとめることにしました。

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1