我正在使用 JQuery 和 HTML5 画布标签编写一个简单的页面,在其中我通过按“w”向上移动一个形状,“s”向下,“a”向左,“d”向右。我已经完成了所有工作,但我希望形状在敲击键时开始以恒定速度移动。现在有某种保持期,然后运动开始。我怎样才能让运动立即发生?
这是我的代码的重要部分:
<script src="jquery.js"></script>
<script src="JQuery.print.js"></script>
<body>
<canvas id="myCanvas" width="500" height="200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br><br>
start navigating<input type="text" id = "enter"/>
<div id = "soul2">
coords should pop up here
</div>
<div id = "soul3">
key should pop up here
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
//keypress movements
var xtriggered = 0;
var keys = {};
var north = -10;
var east = 10;
var flipednorth = 0;
$(document).ready(function(e){
$("input").keydown(function(){
keys[event.which] = true;
if (event.which == 13) {
event.preventDefault();
}
//press w for north
if (event.which == 87) {
north++;
flipednorth--;
}
//press s for south
if (event.which == 83) {
north--;
flipednorth++;
}
//press d for east
if (event.which == 68) {
east++;
}
//press a for west
if (event.which == 65) {
east--;
}
var msg = 'x: ' + flipednorth*5 + ' y: ' + east*5;
ctx.beginPath();
ctx.arc(east*6,flipednorth*6,40,0,2*Math.PI);
ctx.stroke();
$('#soul2').html(msg);
$('#soul3').html(event.which );
$("input").css("background-color","#FFFFCC");
});
$("input").keyup(function(){
delete keys[event.which];
$("input").css("background-color","#D6D6FF");
});
});
</script>
如果我不应该发布这么长的代码,请告诉我。