Skip to content

Instantly share code, notes, and snippets.

@PifyZ
Created April 28, 2014 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PifyZ/11377507 to your computer and use it in GitHub Desktop.
Save PifyZ/11377507 to your computer and use it in GitHub Desktop.
control_keyboard.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Contrôle du clavier</title>
<style>
html, body {
background-color: rgb(255, 255, 255);
}
</style>
</head>
<body>
<canvas id="game">Enable Javascript or use a more recent browser.</canvas>
<script src="kb.js"></script>
</body>
</html>
(function() {
var keycode = {
TAB: 9, ENTER: 13, SHIFT: 16, CTRL: 17,
ALT: 18, ESC : 27, SPACE: 32,
LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40,
A: 65, B: 66, C: 67, D: 68, E: 69, F: 70, G: 71, H: 72, I: 73, J: 74, K: 75, L: 76, M: 77,
N: 78, O: 79, P: 80, Q: 81, R: 82, S: 83, T: 84, U: 85, V: 86, W: 87, X: 88, Y: 89, Z: 90,
NUM0: 48, NUM1: 49, NUM2: 50, NUM3: 51, NUM4: 52,
NUM5: 53, NUM6: 54, NUM7: 55, NUM8: 56, NUM9: 57,
NUMPAD0: 96, NUMPAD1: 97, NUMPAD2: 98, NUMPAD3: 99, NUMPAD4: 100,
NUMPAD5: 101, NUMPAD6: 102, NUMPAD7: 103, NUMPAD8: 104, NUMPAD9: 105,
ADD: 107, SUB: 109, MUL: 106, DIV: 111,
CAPSLOCK: 20, PAGEUP: 33, PAGEDOWN: 34, END : 35,
HOME : 36, ISERT : 45, DELETE : 46, NUMLOCK: 144
};
function Keyboard() {
var self = this;
this.init = function() {
this.keys = [];
this.loose = [];
this.last = 0;
this.ktime = 0;
document.addEventListener('keydown', this.onkeydown, false);
document.addEventListener('keyup', this.onkeyup, false);
};
this.update = function() {
this.ktime++;
};
this.onkeyup = function(e) {
self.loose[e.keyCode] = self.ktime;
self.keys[e.keyCode] = null;
};
this.onkeydown = function(e) {
self.keys[e.keyCode] = self.ktime;
};
this.up = function(k) {
return this.keys[this.str_to_code(k)] == null;
};
this.down = function(k) {
return this.keys[this.str_to_code(k)] != null;
};
this.press = function(k) {
return this.keys[this.str_to_code(k)] == this.ktime;
};
this.release = function(k) {
return this.loose[this.str_to_code(k)] == this.ktime;
};
this.str_to_code = function(k) {
k = k.toUpperCase();
if (keycode[k])
return keycode[k];
else
return null;
}
this.init();
}
window.Keyboard = Keyboard;
})();
/* Utilisation
--------------- */
var kb = new Keyboard();
// up = quand touche levée
// down = quand touche appuyée
// release = quand tu lâche le doigt de la touche
// press = quand tu presses la touche
function update() {
if (kb.press('space')) {
console.log('PRESS');
}
if (kb.down('space')) {
console.log('DOWN');
}
if (kb.release('space')) {
console.log('RELEASE');
}
if (kb.up('space')) {
console.log('UP');
}
// Tout à la fin
kb.update();
requestAnimationFrame(update);
}
update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment