HTML and CSS Reference
In-Depth Information
var canvas = document.getElementById('canvas');
function onMouseEvent (event) {
console.log(event.type);
}
canvas.addEventListener('mousedown', onMouseEvent, false);
canvas.addEventListener('mouseup', onMouseEvent, false);
canvas.addEventListener('click', onMouseEvent, false);
canvas.addEventListener('dblclick', onMouseEvent, false);
canvas.addEventListener('mousewheel', onMouseEvent, false);
canvas.addEventListener('mousemove', onMouseEvent, false);
canvas.addEventListener('mouseover', onMouseEvent, false);
canvas.addEventListener('mouseout', onMouseEvent, false);
};
</script>
</body>
</html>
Notice that we're using the same handler function for every mouse event type, and it prints the type of
event that has been dispatched.
Because we can reference only the canvas element, and not what has been drawn to it, we can't add an
event listener to specific lines or shapes. If you've drawn a rectangle to use as a button, the canvas has no
way of determining where the button boundaries are. To detect a button click, it's up to you to capture the
canvas element's mouse event, determine the position relative to the button, and perform the calculation
yourself. As we work through the topic examples, you'll see some ways to do this.
Mouse position
Every mouse event contains two properties to determine the current location of the mouse cursor: pageX
and pageY . By combining these values and the offset of the canvas element, you can determine where on
the canvas element the mouse is. Unfortunately, these mouse event properties are not supported across
all browsers, so in these cases, you can use clientX and clientY .
Having to calculate the offset every time you need the mouse position is a bit unwieldy. Because we want
to keep the examples uncluttered, add this cross-platform mouse position code into an utility function
utils.captureMouse to include in the file utils.js . We import this into our documents:
utils.captureMouse = function (element) {
var mouse = {x: 0, y: 0};
element.addEventListener('mousemove', function (event) {
var x, y;
if (event.pageX || event.pageY) {
x = event.pageX;
y = event.pageY;
} else {
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
 
Search WWH ::




Custom Search