我在canvas
上有一个对象,我想用键盘事件移动
我的事件功能如下
function onKeyDown(evt) {
if (evt.keyCode == 40) { downDown = true;}
if (evt.keyCode == 39) { rightDown = true;}
if (evt.keyCode == 38) { upDown = true;}
if (evt.keyCode == 37) { leftDown = true;}
}
和我的onKeyUp
功能相同,只有false
作为值
然后我将其作为
附加$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
我有一个draw函数,在我的init中作为intv = setInterval(draw, 10);
调用,带有以下语句
if (rightDown) { x += dx;}
if (upDown) { y -= dy;}
if (downDown) { y += dy;}
if (leftDown) {x -= dx;}
除-x方向(左下)之外的所有内容都能正常工作。这样我可以向上,向下和向下移动物体。按下左侧时,对象继续向左移动。我的条件语句设置不正确吗?
答案 0 :(得分:3)
function onKeyUp(evt) {
if (evt.keyCode == 40) { downDown = false;}
...
// v----- capital K ?
if (evt.KeyCode == 37) { leftDown = false;}
}
答案 1 :(得分:1)
您的代码可以有一些改进,就像您不必每次都检查密钥代码一样,您可以重复使用相同的函数来翻转布尔标记。
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
</head>
<body>
<div id="out1"></div>
<div id="out2"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
(function(){
var downDown = false;
var rightDown = false;
var upDown = false;
var leftDown = false;
function onKeyUpDown(evt,isDown) {
var keyCode = evt.keyCode;
jQuery("#out1").html(keyCode);
if (keyCode == 40) { downDown = isDown;}
else if (keyCode == 39) { rightDown = isDown;}
else if (keyCode == 38) { upDown = isDown;}
else if (keyCode == 37) { leftDown = isDown;}
}
jQuery(document).keydown( function(evt){onKeyUpDown(evt,true);}).keyup( function(evt){onKeyUpDown(evt,false);});
window.setInterval(
function(){
var upDownTxt = upDown?"up":"-"; ;
var downDownTxt = downDown?"down":"-";
var leftDownTxt = leftDown?"left":"-";
var rightDownTxt = rightDown?"right":"-";
jQuery("#out2").html(upDownTxt + "<br/>" + downDownTxt + "<br/>" + leftDownTxt + "<br/>" + rightDownTxt );
},
100);
})();
</script>
</body>
</html>
答案 2 :(得分:1)
在这里,我重新考虑了你的代码:
$(function() {
var x = 150,
y = 150,
dx = 2,
dy = 2,
canvas = $('#canvas'),
ctx = canvas[0].getContext('2d'),
width = canvas.width(),
height = canvas.height(),
keys = {},
intervalId = 0;
function circle(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
$(document).keydown(function(e) { keys[e.which] = true; });
$(document).keyup(function(e) { keys[e.which] = false; });
intervalId = setInterval(function() {
ctx.clearRect(0, 0, width, height);
x = x - (keys['37'] ? dx : 0) + (keys['39'] ? dx : 0);
y = y - (keys['38'] ? dy : 0) + (keys['40'] ? dy : 0);
circle(x, y, 10);
}, 20);
});