0
<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()
功能?動畫的keydown控件
好吧,OP製作使用''作爲''的一個錯誤,你不必遵循... –
Passerby
謝謝你,固定的! – Tony