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


ez3d.html
<!doctype html>
<head>
<meta charset="UTF-8">
<title>ez3d</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 = 5;
const dt = 0.1;
 
var center_x;
var center_y;
var scale;
var ctx;
 
const vertices = [
{x:0, y:0, z:0},
{x:1, y:0, z:0},
{x:1, y:0, z:1},
{x:0, y:0, z:1},
{x:0, y:1, z:0},
{x:1, y:1, z:0},
{x:1, y:1, z:1},
{x:0, y:1, z:1},
];
 
const indices = [0,1, 1,2, 2,3, 3,0, 4,5, 5,6, 6,7, 7,4, 0,4, 1,5, 2,6, 3,7];
 
function init() {
	center_x = canvas1.width / 2;
	center_y = canvas1.height / 2;
	scale = Math.min(center_x, center_y);
 
	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
	if (pos_z < 0.1) pos_z = 0.1;
 
	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.toFixed(1) +
		" y=" + pos_y.toFixed(1) +
		" z=" + pos_z.toFixed(1) +
		" fps=" + fps;
 
	//
	var vs = new Array(vertices.length);
	for (var i = 0; i < vertices.length; i++) {
		var vertex = vertices[i];
		var x = pos_x + vertex.x;
		var y = pos_y + vertex.y;
		var z = pos_z + vertex.z;
 
		var v = {};
		v.x = center_x + (x / z) * scale;
		v.y = center_y - (y / z) * scale;
		vs[i] = v;
	}
 
	ctx.fillRect(0, 0, canvas1.width, canvas1.height);
 
	ctx.beginPath();
	for (var i = 0; i < indices.length; ) {
		var v1 = vs[indices[i++]];
		var v2 = vs[indices[i++]];
		ctx.moveTo(v1.x, v1.y);
		ctx.lineTo(v2.x, v2.y);
	}
	ctx.closePath();
	ctx.stroke();
}
 
</script>
</head>
 
<body onload="init();">
<canvas id="canvas1" width=640 height=480></canvas>
<div id="output"></div>
WASD PageUp/PageDown<br>
</body>
 
最終更新:2015年05月20日 11:35