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