I am implementing a game using javascript, jquery, and canvas tags. How can I prevent the browser from processing keyboard shortcuts when the canvas tags have a focus? I have tried event.stopPropagation () and it has no effect.
I can select keyboard events However, when the user presses the space bar, the web page scrolls down in Firefox. The same problem is with the arrow keys
The basic problem is that by default the browser canvas is not "focusable" Does. Setting up tabindex
on the canvas is best done:
$ ("# canvas") // Keep the tab index to ensure the canvas keeps focusing .attr ("Tabindex", "0") // Keep the mouse override to prevent default browser controls from appearing. Footprint (function) ($ (this). Focus (); return returned;}) .keyword (function () {/ * ... game logic ... * / incorrect return;});
If for any reason you can not set to tabindex
, you can make the canvas "focusable" by setting up contentEditable
Can add edit material to help ensure that the canvas retains the focus $ ("# canvas"). Ether ("content editable", "true") $ ("# canvas") [0] .contentEditable = true;
This is basically the solution I came across, but in my opinion it is a little less than the tabindex
option.
One more thing to consider is that the browsers outline the content editable elements along the border. This can be closed to some users. Fortunately, you can get rid of this bit of CSS:
#canvas {outline: none; }
I tested both solutions in Chrome 3/4/5 and Firefox 3.0 / 3.5 / 3.6 on Windows XP, Mac OSX and Linux. Here's an example:
No comments:
Post a Comment