マウスストーカー(マウスカーソルに追従する点)を実装
マウスストーカー実装しました。
あくまで一例として、実装する際の参考になりましたら幸いです。
【実装例】
カーソル.mp4【手順】
①マウスストーカーの要素をbaseのdiv直下に作成、任意のIDを付与し、絶対配置にする。
②マウスストーカー要素の中にhover時に表示したい画像を配置し任意のIDを付与する。
③<head>内末尾に以下のコードを挿入
<style>
#マウスストーカーに指定したID {
position: absolute;
width: 12px;
height: 12px;
background-color: #FFF;
z-index: 1;
pointer-events: none;
mix-blend-mode: difference;
transform: translate(-50%, -50%);
transition: width 0.2s ease, height 0.2s ease;
}
#画像に指定したID {
width: 20px;
height: 20px;
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease;
}
</style>※大きさやz-indexなどはサイト要件に沿って変更してください。STUDIOのエディター上で指定すればこちらに記述する必要はございません。
④<body>内末尾に以下のコードを挿入
<script>
function moveTowards(current, target, speed) {
const distance = Math.hypot(target.x - current.x, target.y - current.y);
const angle = Math.atan2(target.y - current.y, target.x - current.x);
const x = current.x + Math.cos(angle) * Math.min(speed, distance);
const y = current.y + Math.sin(angle) * Math.min(speed, distance);
return { x, y };
}
const cursor = document.getElementById('マウスストーカーに付与したID');
let mouseX = 0;
let mouseY = 0;
let cursorX = 0;
let cursorY = 0;
const speed = 20;
function updateCursor() {
const newPos = moveTowards({ x: cursorX, y: cursorY }, { x: mouseX, y: mouseY }, speed);
cursorX = newPos.x;
cursorY = newPos.y;
cursor.style.transform = `translate(${cursorX - cursor.offsetWidth / 2}px, ${cursorY - cursor.offsetHeight / 2}px)`;
requestAnimationFrame(updateCursor);
}
updateCursor();
document.addEventListener('mousemove', (e) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
const cursorImg = document.getElementById('画像に付与したID');
document.querySelectorAll('a, button').forEach(element => {
element.addEventListener('mouseover', function() {
// Enlarge the cursor and show the image when hover on a or button
cursor.style.width = '100px';
cursor.style.height = '100px';
cursorImg.style.opacity = '1';
});
element.addEventListener('mouseout', function() {
// Reset the cursor size and hide the image when mouse leaves a or button
cursor.style.width = '12px';
cursor.style.height = '12px';
cursorImg.style.opacity = '0';
});
});
</script>【注意事項】
・Freeプランでは動作しません。
・ライブプレビューでは動作しません。