開発環境 メモ帳
実行環境 Internet Explorer 11


keyboard2.html
<!doctype html>
<head>
<meta charset="UTF-8">
<title>keyboard2</title>
<script>
 
function Keyboard() {
	var _keys;	// キー状態配列
 
	function KeyDownFunc(e) {
		_keys[e.keyCode] = true;
	}
	function KeyUpFunc(e) {
		_keys[e.keyCode] = false;
	}
	function BlurFunc(e) {
		_keys.length = 0;
	}
 
	this.IsKeyDown = function(keyCode) {
		if (_keys[keyCode]) return true;
		return false;
	};
 
	this.Release = function() {
		document.removeEventListener("keydown", KeyDownFunc);
		document.removeEventListener("keyup", KeyUpFunc);
		window.removeEventListener("blur", BlurFunc);
	};
 
	(function(){
		_keys = [];
 
		document.addEventListener("keydown", KeyDownFunc);
		document.addEventListener("keyup", KeyUpFunc);
		window.addEventListener("blur", BlurFunc);
	})();
}
 
var keyboard = new Keyboard();
 
var sec_sav = -1;
var fps_count = 0;
var fps;
 
var pos_x = 0;
var pos_y = 0;
var pos_z = 0;
const dt = 4;
 
var center_x;
var center_y;
var ctx;
 
function init() {
	center_x = canvas1.width / 2;
	center_y = canvas1.height / 2;
 
	ctx = canvas1.getContext("2d");
	ctx.lineWidth = 1;
	ctx.fillStyle = "CornflowerBlue";
	ctx.strokeStyle = "rgba(0, 0, 0, 1.0)";
 
	setInterval(draw, 1000 / 30);
}
 
function draw() {
	if (keyboard.IsKeyDown(87)) pos_y += dt;	// W
	if (keyboard.IsKeyDown(83)) pos_y -= dt;	// S
	if (keyboard.IsKeyDown(65)) pos_x -= dt;	// A
	if (keyboard.IsKeyDown(68)) pos_x += dt;	// D
	if (keyboard.IsKeyDown(33)) pos_z += dt;	// PageUp
	if (keyboard.IsKeyDown(34)) pos_z -= dt;	// PageDown
 
	var sec = (new Date()).getSeconds();
	if (sec_sav != sec) {
		sec_sav = sec;
		fps = fps_count;
		fps_count = 0;
	}
	fps_count++;
 
	output.innerHTML = "x=" + pos_x + " y=" + pos_y + " z=" + pos_z + " fps=" + fps;
 
	ctx.fillRect(0, 0, canvas1.width, canvas1.height);
	ctx.strokeRect(center_x + pos_x, center_y - pos_y, 100, 100);
}
 
</script>
</head>
 
<body onload="init();">
<canvas id="canvas1" width=640 height=480></canvas>
<div id="output"></div>
WASD PageUp/PageDown<br>
</body>
 
最終更新:2015年05月19日 20:27