On Mon, Jun 14, 2010 at 3:56 PM, Simon Pieters <sim...@opera.com> wrote:
> On Tue, 15 Jun 2010 00:16:13 +0200, Kornel Lesinski <kor...@geekhood.net>
> wrote:
>
>> On Mon, 14 Jun 2010 20:38:07 +0100, Carlos Andrés Solís
>> <csol...@gmail.com> wrote:
>>
>>> Hello! I've been noticing a problem in many HTML5 test apps, very
>>> especially games. When the directional arrow buttons are pressed, the screen
>>> scrolls.
>>> This is a problem that, as far as I know, Flash had solved by changing
>>> the focus of the application to the app. Is this doable in HTML5?
>>
>> Yes. It's possible already — page just has to return false from keypress
>> handler:
>>
>> window.onkeypress = function(){return false}
>>
>> That's just one line that, unfortunately, many web-based games forget to
>> include.
>
> If a game is embedded in a page with other content, it could make the
> <canvas> (or whatever) focusable with tabindex='0' and only disable keys
> when the game has focus. It could also be nice and only disable the keys it
> chooses to use.
>
> <script>
> var mapping = {37: 'left', 38: 'up', 39: 'right', 40:'down'}
> function press(e) {
>  if (!e.shiftKey && !e.ctrlKey && !e.metaKey && e.keyCode > 36 && e.keyCode
> < 41) {
>    var ctx = e.target.getContext('2d');
>    ctx.clearRect(0, 0, e.target.width, e.target.height);
>    ctx.fillText(mapping[e.keyCode], 20, 20);
>    e.preventDefault();
>  }
> }
> </script>
> <canvas tabindex=0 onkeypress=press(event)></canvas>
>
> In Opera, I can scroll using the arrow keys, navigate to the game, interact
> with it using the arrow keys without it scrolling the page, and navigate
> away from it using spatnav (shift+arrow keys).

Random note: the keypress event isn't interoperably supported in this
area - in IE and webkit-based browsers, keys that don't generate a
character won't generate a keypress event.  You can use keydown to
capture the press instead.

~TJ

Reply via email to