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:

FunctionGetpointoncanvas (canvas, x, y ){

VaRBBox = canvas. getboundingclientrect ();

Return{X: X-bBox. Left * (canvas. width/bBox. width ),

Y: Y
-BBox. Top * (canvas. Height/bBox. Height)

};

}

Keyboard Events:

HTML5 canvas does not support keyboard event monitoring and acquisition. There are two common methods to solve this problem:

I. Canvas keyboard event monitoring and handling through windows objects
// Key event-Use window as object

Window. addeventlistener ('keylow', dokeydown,True);

2. Add other DOM elements that support Keyboard Events to the canvas object to support Keyboard Events.

<Canvas
Id ="Event_canvas"Tabindex ="0"> </Canvas>

// Key event-use Dom element asobject

Canvas. addeventlistener ('keylow', dokeydown,True);

Canvas. Focus ();

Tabindex is an HTML5 Dom element and supports Keyboard Events.

Demonstration: a rectangle that can be moved from top to bottom of the keyboard:


A complete DEMO code for mouse and keyboard events is as follows:

var tempContext = null; // global variable 2d contextvar started = false;var mText_canvas = null;var x = 0, y =0;window.addwindow.onload = function() {var canvas = document.getElementById("event_canvas");console.log(canvas.parentNode.clientWidth);canvas.width = canvas.parentNode.clientWidth;canvas.height = canvas.parentNode.clientHeight;if (!canvas.getContext) {    console.log("Canvas not supported. Please install a HTML5 compatible browser.");    return;}// get 2D context of canvas and draw rectangeltempContext = canvas.getContext("2d");tempContext.fillStyle="blue";x = canvas.width/2;y = canvas.height/2;tempContext.fillRect(x, y, 80, 40);        // key event - use DOM element as object        canvas.addEventListener('keydown', doKeyDown, true);        canvas.focus();          // key event - use window as object        window.addEventListener('keydown', doKeyDown, true);                // mouse event        canvas.addEventListener("mousedown", doMouseDown, false);        canvas.addEventListener('mousemove', doMouseMove, false);        canvas.addEventListener('mouseup',   doMouseUp, false);}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)};}function doKeyDown(e) {var keyID = e.keyCode ? e.keyCode :e.which;if(keyID === 38 || keyID === 87)  { // up arrow and WclearCanvas();y = y - 10;tempContext.fillRect(x, y, 80, 40);e.preventDefault();}if(keyID === 39 || keyID === 68)  { // right arrow and DclearCanvas();x = x + 10;tempContext.fillRect(x, y, 80, 40);e.preventDefault();}if(keyID === 40 || keyID === 83)  { // down arrow and SclearCanvas();y = y + 10;tempContext.fillRect(x, y, 80, 40);e.preventDefault();}if(keyID === 37 || keyID === 65)  { // left arrow and AclearCanvas();x = x - 10;tempContext.fillRect(x, y, 80, 40);e.preventDefault();}}function clearCanvas() {tempContext.clearRect(0, 0, 500, 500)}function doMouseDown(event) {var x = event.pageX;var y = event.pageY;var canvas = event.target;var loc = getPointOnCanvas(canvas, x, y);console.log("mouse down at point( x:" + loc.x + ", y:" + loc.y + ")");tempContext.beginPath();tempContext.moveTo(loc.x, loc.y);started = true;}function doMouseMove(event) {var x = event.pageX;var y = event.pageY;var canvas = event.target;var loc = getPointOnCanvas(canvas, x, y);if (started) {tempContext.lineTo(loc.x, loc.y);tempContext.stroke();}}function doMouseUp(event) {console.log("mouse up now");    if (started) {    doMouseMove(event);        started = false;}}

HTML section:

<body>

I think it is good. Please support it. Thank you !!

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.