HTML and CSS Reference
In-Depth Information
}
x -= element.offsetLeft;
y -= element.offsetTop;
mouse.x = x;
mouse.y = y;
}, false);
return mouse;
};
This function takes a DOM element as an argument, attaches a mousemove event handler to it, and returns
an object with x and y properties. When the mouse moves over the element, the event handler calculates
the mouse position using the event's location (as supported by the browser) and the document offset
position of the element. It then assigns these values to the object we returned, which we can access from
our main script. The mouse x and y positions are relative to the top-left corner of the element, which is the
coordinate (0, 0).
For example, you invoke this function at the start of the script, passing the canvas element as an
argument:
var canvas = document.getElementById('canvas'),
mouse = utils.captureMouse(canvas);
After the mouse object has been initialized, you can query its x and y properties whenever you need to
determine the current location of the mouse cursor. Here's a complete example that demonstrates how
this function is used throughout the rest of the topic:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mouse Position</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
mouse = utils.captureMouse(canvas);
canvas.addEventListener('mousedown', function () {
console.log("x: " + mouse.x + ", y: " + mouse.y);
}, false);
};
</script>
</body>
</html>
Run this file ( 04-mouse-position.html ) in your browser with the debugging console open. Make sure
you've included the utils.captureMouse function in utils.js and imported that file into the document.
Search WWH ::




Custom Search