我已经按照教程制作了一个简单的 HTML 画布游戏(链接在这里)。游戏保存在一个 javascript 文件中,我不知道如何测试它。我环顾四周,发现它应该从一个 html 页面运行,所以我写到这里:
<html>
<head>
<script language="javascript" src="main.js" type="text/javascript"/>
</script>
</head>
<body>
</body>
</html>
这没有任何作用,这是我所期望的。但是,我不知道该怎么做才能运行它。我很感激对此的任何意见。谢谢
编辑* 它归结为 javascript 文件中的错误。下面是我的代码:
//canvas
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
canvas.width=512;
canvas.height=480;
document.body.appendChild(canvas);
//background img
var bgready=false;
var bgimage=new Image();
bgimage.onload=function(){
bgready=true;
};
bgimage.src="images/bg_space.png";
//player img
var playerready=false;
var playerimage=new Image();
playerimage.onload=function(){
playerready=true;
};
playerimage.src="images/spr_player.png";
//enemy img
var enemyready=false;
var enemyimage=new Image();
enemyimage.onload=function(){
enemyready=true;
};
enemyimage.src="images/spr_enemy1.png";
//objects
var player={
speed:256
};
var enemy={};
var kills=0;
//handle keys
var keysdown={};
addEventListener("keydown",function(e){
keysdown[e.keycode]=true;
},false);
addEventListener("keyup",function(e){
delete keysdown[e.keyCode];
},false);
//reset
var reset=function(){
player.x=canvas.width/2;
player.y=canvas.height/2
enemy.x=32+(Math.random()*(canvas.width-64));
enemy.y=32+(Math.random()*(canvas.height-64));
};
//update
var update=function(modifier){
if (38 in keysdown){
player.y-=player.speed*modifier;//up
}
if (40 in keysdown){
player.y+=player.speed*modifier;//down
}
if (37 in keysdown){
player.x-=player.speed*modifier;//left
}
if (39 in keysdown){
player.x+=player.speed*modifier;//right
}
if(
player.x<=(enemy.x+32)
&& enemy.x<=(player.x+32)
&& player.y<=(enemy.y+32)
&& enemy.y<=(player.y+32)
){
++kills;
reset();
}
};
//render
var render=function(){
if (bgready){
ctx.drawImage(bgimage,0,0);
}
if (playerready){
ctx.drawImage(playerimage,player.x,player.y);
}
if (enemyready){
ctx.drawImage(enemyimage,enemy.x,enemy.y);
}
//score
ctx.fillStyle="rgb(250,250,250)";
ctx.font="24px Helvetica";
ctx.textAlign="left";
ctx.textBaseline="top";
ctx.fillText("kills: "+kills,32,32);
};
//mainloop
var main=function(){
var now=Date.now();
var delta=now-then;
update(delta/1000);
render();
then=now;
};
//init
reset();
var then=Date.now();
setInterval(main,1);
我现在至少查看了我的脚本和教程脚本 7 次。我确实发现我加载图像错误,但现在它所做的只是显示图像。我根本无法移动播放器。