gamepad-tester/index.html
Gregg Tavares 895e0a3491 show id
2019-02-22 19:41:28 +09:00

100 lines
2.4 KiB
HTML

<style>
body {
background: #444;
color: white;
font-family: monospace;
}
#gamepads>* {
background: #333;
padding: 1em;
}
</style>
<body>
<h1>HTML5 Gamepad Test</h1>
<div>running: <span id="running"></span></div>
<div id="gamepads"></div>
</body>
<script>
const runningElem = document.querySelector('#running');
const gamepadsElem = document.querySelector('#gamepads');
const gamepadsByIndex = {};
function addGamepad(gamepad) {
console.log('add:', gamepad.index);
const elem = document.createElement('pre');
gamepadsElem.appendChild(elem);
gamepadsByIndex[gamepad.index] = {
gamepad,
elem,
};
}
function removeGamepad(gamepad) {
const info = gamepadsByIndex[gamepad.index];
if (info) {
delete gamepadsByIndex[gamepad.index];
info.elem.parentElement.removeChild(info.elem);
}
}
function addGamepadIfNew(gamepad) {
if (!gamepadsByIndex[gamepad.index]) {
addGamepad(gamepad);
}
}
function handleConnect(e) {
console.log('connect');
addGamepadIfNew(e.gamepad);
}
function handleDisconnect(e) {
console.log('disconnect');
removeGamepad(e.gamepad);
}
const t = String.fromCharCode(0x26AA);
const f = String.fromCharCode(0x26AB);
function onOff(v) {
return v ? t : f;
}
const keys = ['id', 'connected', 'mapping', /*'timestamp'*/];
function processController(info) {
const {elem, gamepad} = info;
const lines = [`gamepad : ${gamepad.index}`];
for (const key of keys) {
lines.push(`${key.padEnd(9)}: ${gamepad[key]}`);
}
lines.push(`axes : [${gamepad.axes.map((v, ndx) => `${ndx}: ${v.toFixed(2).padStart(5)}`).join(', ')} ]`);
lines.push(`buttons : [${gamepad.buttons.map((v, ndx) => `${ndx}: ${onOff(v.pressed)} ${v.value.toFixed(2)}`).join(', ')} ]`);
elem.textContent = lines.join('\n');
}
function addNewPads() {
const gamepads = navigator.getGamepads();
for (let i = 0; i < gamepads.length; i++) {
const gamepad = gamepads[i]
if (gamepad) {
addGamepadIfNew(gamepad);
}
}
}
window.addEventListener("gamepadconnected", handleConnect);
window.addEventListener("gamepaddisconnected", handleDisconnect);
function process() {
runningElem.textContent = ((performance.now() * 0.001 * 60 | 0) % 100).toString().padStart(2, '0');
addNewPads(); // some browsers add by polling, others by event
Object.values(gamepadsByIndex).forEach(processController);
requestAnimationFrame(process);
}
requestAnimationFrame(process);
</script>