How to check keyboard state while painting on HTML5 canvas?

I'm just mucking around a bit with HTML5 canvas and painting. I happened to find this article by Opera that describes well how to set up a simple application.

I would like to extend it so that the user may set up a vanishing point (1 point perspective) that may be used to constrain painting. To allow this I need to figure out a way to define some modifier keys to limit the result (i.e. constraints map as (key=>axis) a=>x, s=>y, d=>z).

Is there some way to check out which key the user has pressed while handling the "mousedown" event?

Upvotes: 0

Views: 2067

Answers (1)

markcial
markcial

Reputation: 9333

AFAIK it only will work when the document have focus.

You should add a listener to the body attending for the key press event, when it has triggered, you store it in a variable emptying it afterwards when user triggers key release, an example should be like this :

document.body.onkeydown=function(evt){evt=evt?evt:window.event;console.log(evt)};
document.body.onkeyup=function(evt){evt=evt?evt:window.event;console.log(evt)};

then you only should identify evt.keyCode and act with it.

You could try third party libraries like shortcut.js too.

Upvotes: 3

Related Questions