<html>
<header>
<link href='css.css' rel='stylesheet'>
<meta charset="UTF-8">
<title> moving box </title>
<script type= 'text/javascript'>
var rectangle = {
x: 100,
y: 100,
width: 100,
height: 100,
};
var mx = 4;
var my = 4;
var cheight = 700;
var cwidth = 700;
var e = event.keyCode;
function checkmx() {
if (rectangle.x + 100 > cwidth){
mx = -4;
}
if (rectangle.x < 0){
mx = 4;
}
}
function checkmy() {
if (rectangle.y + 100 > cheight){
my = -4;
}
if (rectangle.y < 0){
my = 4;
}
}
function keydowncontrol(){
if (e == 37){
mx = -1;
my = 0;
}
if (e == 38){
mx = 0;
my = -1;
}
if (e == 39){
mx = 1;
my = 0;
}
if (e == 40){
mx = 0;
my = 1;
}
//if (e == 35){
//mx = 0
//mx = 0
//}
}
function draw() {
checkmx();
checkmy();
keydowncontrol();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var nextx = rectangle.x + mx;
var nexty = rectangle.y + my;
rectangle.x = nextx
rectangle.y = nexty
ctx.clearRect(0, 0, cwidth, cheight);
ctx.beginPath();
ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = '#FF0000';
ctx.fill();
ctx.stroke();
}
function init() {
checkmx();
checkmy();
window.onkeydown = keydowncontrol();// how can does this notice the key pressed
draw();
}
</script>
</header>
<body onload='setInterval(init,10)'>
<canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>
ボックスをアニメーション化しようとしています。window.onkeydown
とがどのように機能するかわかりませんevent.keycode
。私の目標は、押されたキーに応じて変数mx
と変数を変更することです。関数または関数にある必要がありますかmy
?keydowncontrol()
draw()
init()