Permalink
Browse files

Add keys example.

  • Loading branch information...
1 parent f66a813 commit 78fbaf10fbca10a7144eeb030a0e5edac0e801cf @wtaysom committed Mar 30, 2012
Showing with 261 additions and 5 deletions.
  1. +184 −0 keymaster.js
  2. +13 −0 keys.html
  3. +56 −0 keys.js
  4. +8 −5 notes.md
View
@@ -0,0 +1,184 @@
+// keymaster.js
+// (c) 2011 Thomas Fuchs
+// keymaster.js may be freely distributed under the MIT license.
+
+;(function(global){
+ var k,
+ _handlers = {},
+ _mods = { 16: false, 18: false, 17: false, 91: false },
+ _scope = 'all',
+ // modifier keys
+ _MODIFIERS = {
+ '': 16, shift: 16,
+ '': 18, alt: 18, option: 18,
+ '': 17, ctrl: 17, control: 17,
+ '': 91, command: 91
+ },
+ // special keys
+ _MAP = {
+ backspace: 8, tab: 9, clear: 12,
+ enter: 13, 'return': 13,
+ esc: 27, escape: 27, space: 32,
+ left: 37, up: 38,
+ right: 39, down: 40,
+ del: 46, 'delete': 46,
+ home: 36, end: 35,
+ pageup: 33, pagedown: 34,
+ ',': 188, '.': 190, '/': 191,
+ '`': 192, '-': 189, '=': 187,
+ ';': 186, '\'': 222,
+ '[': 219, ']': 221, '\\': 220
+ };
+
+ for(k=1;k<20;k++) _MODIFIERS['f'+k] = 111+k;
+
+ // IE doesn't support Array#indexOf, so have a simple replacement
+ function index(array, item){
+ var i = array.length;
+ while(i--) if(array[i]===item) return i;
+ return -1;
+ }
+
+ // handle keydown event
+ function dispatch(event){
+ var key, handler, k, i, modifiersMatch;
+ key = event.keyCode;
+
+ // if a modifier key, set the key.<modifierkeyname> property to true and return
+ if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
+ if(key in _mods) {
+ _mods[key] = true;
+ // 'assignKey' from inside this closure is exported to window.key
+ for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
+ return;
+ }
+
+ // see if we need to ignore the keypress (ftiler() can can be overridden)
+ // by default ignore key presses if a select, textarea, or input is focused
+ if(!assignKey.filter.call(this, event)) return;
+
+ // abort if no potentially matching shortcuts found
+ if (!(key in _handlers)) return;
+
+ // for each potential shortcut
+ for (i = 0; i < _handlers[key].length; i++) {
+ handler = _handlers[key][i];
+
+ // see if it's in the current scope
+ if(handler.scope == _scope || handler.scope == 'all'){
+ // check if modifiers match if any
+ modifiersMatch = handler.mods.length > 0;
+ for(k in _mods)
+ if((!_mods[k] && index(handler.mods, +k) > -1) ||
+ (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
+ // call the handler and stop the event if neccessary
+ if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
+ if(handler.method(event, handler)===false){
+ if(event.preventDefault) event.preventDefault();
+ else event.returnValue = false;
+ if(event.stopPropagation) event.stopPropagation();
+ if(event.cancelBubble) event.cancelBubble = true;
+ }
+ }
+ }
+ }
+ };
+
+ // unset modifier keys on keyup
+ function clearModifier(event){
+ var key = event.keyCode, k;
+ if(key == 93 || key == 224) key = 91;
+ if(key in _mods) {
+ _mods[key] = false;
+ for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = false;
+ }
+ };
+
+ function resetModifiers() {
+ for(k in _mods) _mods[k] = false;
+ for(k in _MODIFIERS) assignKey[k] = false;
+ }
+
+ // parse and assign shortcut
+ function assignKey(key, scope, method){
+ var keys, mods, i, mi;
+ if (method === undefined) {
+ method = scope;
+ scope = 'all';
+ }
+ key = key.replace(/\s/g,'');
+ keys = key.split(',');
+
+ if((keys[keys.length-1])=='')
+ keys[keys.length-2] += ',';
+ // for each shortcut
+ for (i = 0; i < keys.length; i++) {
+ // set modifier keys if any
+ mods = [];
+ key = keys[i].split('+');
+ if(key.length > 1){
+ mods = key.slice(0,key.length-1);
+ for (mi = 0; mi < mods.length; mi++)
+ mods[mi] = _MODIFIERS[mods[mi]];
+ key = [key[key.length-1]];
+ }
+ // convert to keycode and...
+ key = key[0]
+ key = _MAP[key] || key.toUpperCase().charCodeAt(0);
+ // ...store handler
+ if (!(key in _handlers)) _handlers[key] = [];
+ _handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods });
+ }
+ };
+
+ function filter(event){
+ var tagName = (event.target || event.srcElement).tagName;
+ // ignore keypressed in any elements that support keyboard data input
+ return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
+ }
+
+ // initialize key.<modifier> to false
+ for(k in _MODIFIERS) assignKey[k] = false;
+
+ // set current scope (default 'all')
+ function setScope(scope){ _scope = scope || 'all' };
+ function getScope(){ return _scope || 'all' };
+
+ // delete all handlers for a given scope
+ function deleteScope(scope){
+ var key, handlers, i;
+
+ for (key in _handlers) {
+ handlers = _handlers[key];
+ for (i = 0; i < handlers.length; ) {
+ if (handlers[i].scope === scope) handlers.splice(i, 1);
+ else i++;
+ }
+ }
+ };
+
+ // cross-browser events
+ function addEvent(object, event, method) {
+ if (object.addEventListener)
+ object.addEventListener(event, method, false);
+ else if(object.attachEvent)
+ object.attachEvent('on'+event, function(){ method(window.event) });
+ };
+
+ // set the handlers globally on document
+ addEvent(document, 'keydown', dispatch);
+ addEvent(document, 'keyup', clearModifier);
+
+ // reset modifiers to false whenever the window is (re)focused.
+ addEvent(window, 'focus', resetModifiers);
+
+ // set window.key and window.key.set/get/deleteScope, and the default filter
+ global.key = assignKey;
+ global.key.setScope = setScope;
+ global.key.getScope = getScope;
+ global.key.deleteScope = deleteScope;
+ global.key.filter = filter;
+
+ if(typeof module !== 'undefined') module.exports = key;
+
+})(this);
View
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Using Keymaster Library</title>
+</head>
+<body>
+ <canvas id="canvas" width="480" height="320"
+ style="background-color: black;"></canvas>
+ <script src="keymaster.js"></script>
+ <script src="keys.js"></script>
+</body>
+</html>
View
56 keys.js
@@ -0,0 +1,56 @@
+var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+var mouseDown = false;
+var width = 65;
+var height = 65;
+var x = (canvas.width - width) / 2;
+var y = (canvas.height - height) / 2;
+
+key('w', function() {
+ y -= 10;
+ redraw();
+});
+
+key('a', function() {
+ x -= 10;
+ redraw();
+});
+
+key('s', function() {
+ y += 10;
+ redraw();
+});
+
+key('d', function() {
+ x += 10;
+ redraw();
+});
+
+key('up', function() {
+ height -= 10;
+ redraw();
+});
+
+key('left', function() {
+ width -= 10;
+ redraw();
+});
+
+key('down', function() {
+ height += 10;
+ redraw();
+});
+
+key('right', function() {
+ width += 10;
+ redraw();
+});
+
+function redraw() {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.fillStyle = 'red';
+ ctx.fillRect(x, y, width, height);
+}
+
+redraw();
View
@@ -113,10 +113,17 @@ Feel free to email me or find me on Skype (username wtaysom) for more hints.
## Topics
-Mouse events, keyboard events, libraries
+Mouse events, keyboard events, libraries.
!! parameter slider using [Dragdealer JS](http://code.ovidiu.ch/dragdealer/)
+## Example
+
+* interaction.html.
+* keys.html.
+* [BrowserQuest](https://hacks.mozilla.org/2012/03/browserquest/) is a demo massively multiplayer game.
+* [Dragdealer JS](http://code.ovidiu.ch/dragdealer/) is an awesome little slider.
+
## Tools
* DigitalColor Meter application to get a pixel level inspection of what's going on.
@@ -125,7 +132,3 @@ Mouse events, keyboard events, libraries
## Tutorials
* [Canvas Mouse Tutorial](http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/) provides one way complete way to find mouse where the mouse is.
-
-## Example
-
-[BrowserQuest](https://hacks.mozilla.org/2012/03/browserquest/) is a demo massively multiplayer game.

0 comments on commit 78fbaf1

Please sign in to comment.