HTML5 Canvas mouse and keyboard events

Source: Internet
Author: User

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)

};

}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.