Keyboard handler

This commit is contained in:
Evert Prants 2018-08-19 13:50:13 +03:00
parent 432b220ecb
commit 05da6a7893
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
3 changed files with 140 additions and 1 deletions

2
dist/dwelibs.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -9,5 +9,8 @@ require('./math.js')
// Mouse helpers
require('./mouse.js')
// Keyboard helpers
require('./keyboard.js')
// Image helpers
require('./image.js')

136
src/keyboard.js Normal file
View File

@ -0,0 +1,136 @@
DWE.Keyboard = {}
var keyList = {}
var previousKeyList = {}
var specialKeyMap = {
'backspace': 8,
'tab': 9,
'enter': 13,
'shift': 16,
'ctrl': 17,
'alt': 18,
'pausebreak': 19,
'capslock': 20,
'escape': 27,
'pgup': 33,
'pgdown': 34,
'end': 35,
'home': 36,
'left': 37,
'up': 38,
'right': 39,
'down': 40,
'insert': 45,
'delete': 46,
'left-window': 91,
'right-window': 92,
'select': 93,
'numpad0': 96,
'numpad1': 97,
'numpad2': 98,
'numpad3': 99,
'numpad4': 100,
'numpad5': 101,
'numpad6': 102,
'numpad7': 103,
'numpad8': 104,
'numpad9': 105,
'multiply': 106,
'add': 107,
'subtract': 109,
'decimal': 110,
'divide': 111,
'f1': 112,
'f2': 113,
'f3': 114,
'f4': 115,
'f5': 116,
'f6': 117,
'f7': 118,
'f8': 119,
'f9': 120,
'f10': 121,
'f11': 122,
'f12': 123,
'numlock': 144,
'scrolllock': 145,
'semi-colon': 186,
'equals': 187,
'comma': 188,
'dash': 189,
'period': 190,
'fwdslash': 191,
'grave': 192,
'open-bracket': 219,
'bkslash': 220,
'close-braket': 221,
'single-quote': 222
}
DWE.Keyboard.toggleKey = function (keyCode, on) {
// Find key in special key list
var key = null
for (let k in specialKeyMap) {
let val = specialKeyMap[k]
if (keyCode === val) {
key = k
break
}
}
// Use fromCharCode
if (!key) {
key = String.fromCharCode(keyCode).toLowerCase()
}
keyList[key] = (on === true)
}
DWE.Keyboard.keyDown = function (e) {
var keycode
if (window.event)
keycode = window.event.keyCode
else if (e)
keycode = e.which
DWE.Keyboard.toggleKey(keycode, true)
}
DWE.Keyboard.keyUp = function (e) {
var keycode
if (window.event)
keycode = window.event.keyCode
else if (e)
keycode = e.which
DWE.Keyboard.toggleKey(keycode, false)
}
function down (key) {
return keyList[key] != null ? keyList[key] : false
}
function downLast (key) {
return previousKeyList[key] != null ? previousKeyList[key] : false
}
DWE.Keyboard.isDown = function (key) {
return down(key) && downLast(key)
}
DWE.Keyboard.isUp = function (key) {
return !DWE.Keyboard.isDown(key)
}
DWE.Keyboard.isPressed = function (key) {
return down(key) === true && downLast(key) === false
}
DWE.Keyboard.nextIteration = function () {
previousKeyList = {}
for (let k in keyList) {
if (keyList[k] === true) {
previousKeyList[k] = true
}
}
}