マウスを追って目を動かす目玉を HTML/CSS で作成しています.
目玉の中央にマウスを置くと目玉は真っ直ぐ前を向き,マウスを任意の方向に動かすと目玉はその方向に向く,というような完成形をイメージしています.
その際,エレメントの座標の処理をどこかで間違えているようで,思った通りの挙動を示しません.
マウスを目で追う挙動ではなく,その右上を見ている状態です.
JavaScript
1const ball = document.querySelector('.ball'); // 目玉のエレメント 2document.onmousemove = () => { 3 let left2center = document.body.clientWidth / 2; // ウィンドウ左端から中央までの長さ 4 let top2center = document.body.clientHeight / 2; // ウィンドウ上端から中央までの長さ 5 let offsetx = left2center - ball.getBoundingClientRect().left + 0; // ここが不適当? 6 let offsety = top2center - ball.getBoundingClientRect().top + 0; // ここが不適当? 7 8 var x = (event.clientX + offsetx) * 100 / window.innerWidth + "%"; 9 var y = (event.clientY + offsety) * 100 / window.innerHeight + "%"; 10 ball.style.left = x; 11 ball.style.top = y; 12 ball.style.transform = `translate(-${x}, -${y})`; 13}
コード中 offsetx
と offsety
で中央からのずれを表しているつもりなのですが,どこか勘違いをしているようで...
ご教示よろしくお願いします.
HTML
1<!DOCTYPE html> 2<html lang="en" dir="ltr"> 3<head> 4 <link rel="stylesheet" href="style.css"> 5</head> 6<body> 7 <div class="eyes"> 8 <div class="eye"> 9 <div class="ball"></div> 10 </div> 11 </div> 12 <script><!-- 同上 --></script> 13</body> 14</html>
CSS
1body{ 2 margin: 0; 3 padding: 0; 4} 5 6.eyes{ 7 position: absolute; 8 top: 50%; 9 transform: translateY(-50%); 10 width: 100%; 11 text-align: center; 12} 13 14.eye{ 15 width: 10rem; 16 height: 10rem; 17 background: #ddd; 18 display: inline-block; 19 border-radius: 50%; 20 position: relative; 21 overflow: hidden; 22 margin: 2rem; 23} 24 25.ball{ 26 width: 5rem; 27 height: 5rem; 28 background: #000; 29 position: absolute; 30 top: 50%; 31 left: 50%; 32 transform: translate(-50%,-50%); 33 border-radius: 50%; 34 border: 1rem solid #333; 35}
回答1件
あなたの回答
tips
プレビュー