【发布时间】:2014-12-11 08:14:39
【问题描述】:
我正在开发 HTML 5 中的 Stick Hero(著名的 Android 游戏)克隆,我正在尝试实现用于在 Javascript 中捕获 time of key press (right arrow - ASCII 39) 的代码并相应地增长。
<!doctype html>
<html>
<head>
<title> Stuck Hero !</title>
<script src='jquery-2.1.1.min.js'> </script>
</head>
<body>
<canvas id='stuck' height='300' width='500'> </canvas>
</body>
<script>
var stick_size=10;
$(document).ready(function(){
var canvas=$("#stuck")[0];
var ctx=canvas.getContext('2d');
var w=$("#stuck").width();
var h=$("#stuck").height();
var score=0;
var stick=0;
var timeout=0;
console.log(w +" is width and "+h+" is the height ");
paint(w,h,ctx);
score_update(ctx);
});
function score_update(ctx){
//function to print the score
ctx.font = "20px Arial";
ctx.strokeText("Your Score is :",1,300);
console.log("Console Score Printed Successfully");
}
function paint(width,height,ctl) {
var rand = Math.floor(Math.random() * 101);
ctx=ctl;
// function to print different background styles
if(rand %3 ==0) {
ctx.fillStyle = "#F0F0F0";
}
else if(rand %2 == 0){
ctx.fillStyle = "#D0D0D0";
}
else{
ctx.fillStyle = "#C0C0C0";
}
drawing(ctx,width,height);
console.log("Console was Painted Successfully");
}
function drawing(ctx,width,height) {
//filling rectangle
ctx.fillRect(0,0,width,height);
//drawing our hero
ctx.beginPath();
ctx.arc(20, 200, 15 , 0, 2 * Math.PI, false);
ctx.fillStyle = 'green';
ctx.fill();
console.log("Shapes were drawn Successfully");
}
//growing stick
function grow_stick() {
for(lv=200;lv>stick_size;lv++) {
ctx.beginPath();
ctx.moveTo(20,200);
console.log("Moved to 20 , 200 in Canvas");
ctx.lineTo(20,lv);
console.log("Drawing Line from 20 to "+lv);
ctx.stroke();
console.log("Stroke is Done");
}
console.log("Stick was growing Successfully");
}
function clearcanvas(ctl,width,height){
//function to clear the screen data
ctl.clearRect ( 0 , 0 ,width,height );
}
$(document).keydown(function(e){
var key = e.which;
if(key == "39"){ //38 is the code for up key
//event.preventDefault();
console.log("Down key is pressed");
timeout= setInterval(grow_stick);
}
}).bind('keyup', function(e){
if(e.which == "39") {
console.log("Down key pressed is released ");
clearTimeout(timeout);
}
});
</script>
</html>
我有一些问题和澄清
-
如何跟踪按键事件?
我尝试在按键时设置超时功能,当按键被释放时我将释放超时功能(但在 cleartimeout 上有一些问题) -
按键释放后如何不接受任何事件,我必须做其他动画?
还没试过,不知道 -
另一个常见问题
如何准备我作为 HTML5 游戏开发者的心态,欢迎任何参考链接或想法,我知道基本编程
编辑:jsfiddle
【问题讨论】:
-
好问题 +1 你有 jsFiddle 供我们检查吗?
标签: javascript jquery html canvas jquery-events