JavaScript
この記事では、マウスが動いたときに処理を実行するJavaScriptのonmousemoveイベントの基本を説明します。
JavaScript's onmousemove event detects when a user moves the mouse, allowing you to execute code in response to that movement.
onmousemove [event]
onmousemove(または mousemoveイベント)は、ユーザーがマウスを動かしたときに発生するイベントです。特定の要素上でマウスが動いたときに、その動きに応じて処理を実行することができます。
基本的な使い方
JavaScript
element.addEventListener('mousemove', function(event) {
// マウスの位置情報を取得して処理するコード
const x = event.clientX;
const y = event.clientY;
console.log(`マウス座標: (${x}, ${y})`);
});
このコードでは、element上でマウスが動くたびに、マウスの座標がコンソールに表示されます。
用途
- リアルタイムでの描画やアニメーション
- インタラクティブなユーザーインターフェースの実装
- マウスの追跡やカスタムカーソルの表示
注意点
mousemoveイベントは非常に高頻度で発生するため、重い処理を行うとパフォーマンスに影響を与える可能性があります。必要に応じて、requestAnimationFrameやデバウンス処理を用いて負荷を軽減することが推奨されます。
onmousemoveとmousemoveの違い
onmousemoveと mousemoveの違いは、onmousemoveがイベントハンドラプロパティであるのに対し、mousemoveはイベントの種類を表す名前である点です。
具体的には
- onmousemove(イベントハンドラプロパティ)
- DOM要素のプロパティとして存在し、マウスが動いたときに実行したい関数を直接割り当てます。
-
JavaScript
element.onmousemove = function(event) { // マウスが動いたときの処理 }; - mousemove(イベント名)
- addEventListenerメソッドと組み合わせて使用し、イベントリスナーを登録します。
-
JavaScript
element.addEventListener('mousemove', function(event) { // マウスが動いたときの処理 });
まとめると
- onmousemove
- イベントハンドラプロパティで、特定の要素に対して直接関数を割り当てます。
- mousemove
- イベント名で、addEventListenerを使ってリスナーを登録する際に使用します。
なお、JavaScriptは大文字と小文字を区別するため、onMouseMoveや mouseMoveという名称は一般的ではありません。標準的にはすべて小文字の onmousemoveと mousemoveが使用されます。
Sample
HTML
<body id="omm">
<div id="smp"></div>
</body>
JavaScript
let frameId = null;
let latestX = 0;
let latestY = 0;
document.getElementById('omm').addEventListener('mousemove', function(event) {
latestX = event.clientX;
latestY = event.clientY;
if (frameId !== null) return;
frameId = requestAnimationFrame(function() {
document.getElementById('smp').textContent = `マウス座標: (${latestX}, ${latestY})`;
frameId = null;
});
});