Demonstrate HTML5 Canvas mouse events, get the mouse coordinates on the Canvas object, and demonstrate Keyboard Events
Use the keyboard to control the movement of objects on the Canvas.
The Canvas object supports all JavaScript mouse events, including mouse clicks and mouse clicks.
(Mouse Down), Mouse Up, and Mouse Move)
You can add a mouse event to a Canvas in either of the following ways:
// Mouse event
Canvas. addEventListener ("mousedown", doMouseDown, false );
Canvas. addEventListener ('mousemove ', doMouseMove, false );
Canvas. addEventListener ('mouseup', doMouseUp, false );
Another method is called anti-pattern in JavaScript:
Canvas. onmousedown = function (e ){
}
Canvas. onmouseup = function (e ){
}
Canvas. onmousemove = function (e ){
}
Get the coordinates of the mouse over the Canvas object:
Because the coordinates of the mouse on the Canvas cannot be obtained directly from the mouse event on the Canvas
The coordinates of the screen. Therefore, the mouse event e. pageX and e. pageY are used to obtain the mouse position, and then
Canvas. getBoundingClientRect () to obtain the relative position of the Canvas object to the screen.
Get the coordinates of the mouse on the Canvas. The Code is as follows:
Function getPointOnCanvas (canvas, x, y ){
Var bbox = canvas. getBoundingClientRect ();
Return {x: x-bbox. left * (canvas. width/bbox. width ),
Y: y-bbox. top * (canvas. height/bbox. height)
};
}