模擬微信打飛機遊戲,JavaScript+HTML5+css實現,隨後版本可能移植到Android和IOS.
首個版本里,僅實現按住鍵盤移動飛機移動. 不必解釋過多,代碼裏面有註釋.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hit Flyer</title>
<!--
Email: [email protected]
-->
<!--
I perfect do not use jQuery.
As jQuery is so famous,some learners learn jQuery,then JavaScript,and me too.
I am here try to show you that JavaScript can do what jQuery does in a easy way.
-->
<!--
At the this Version,
the player can move by click the keyboard.
-->
<style type="text/css">
canvas#mycanvas {
/*let canvas be center */
position: absolute;
margin: auto auto;
top: 5px;
left: 5px;
right: 5px;
bottom: 5px;
background-color: black;
border: 1px solid #d3d3d3;
}
</style>
</head>
<body>
<!-- do not know why set the "width" and "height" as a style,
not as attribute,will cause draw rectangle'width wrong
-->
<canvas id="mycanvas" width="400" height="600">
</canvas>
<script>
/**
* put script at the bottom of body document.
* or you should add code as
* <code>
* window.addEventListener("load",function(){
* //todo put your code
* });
*
*</code>
*/
var mycanvas=document.getElementById("mycanvas");
var ctx=mycanvas.getContext("2d");
var canWidth=mycanvas.width;
var canHeight=mycanvas.height;
/*
* We will only have one instance player,so create a player object directly.
*
*/
var player={
width:20,
height:20,
step:5,//when press key,the player will move.
//here just use Rectangle as Plane,if you have Plane image...
// then maybe color properties can be removed.
color:"red",
position:{
x:0,
y:0
}
};
/*
* The player display method, and it will show at (x,y).
*/
player.display=function(x,y){
this.position.x=x;
this.position.y=y;
//save the Context status. then restore it,as "ctx.restore" shows
ctx.save();
ctx.fillStyle=this.color;
//here just use Rectangle as Plane,if you have Plane image...
ctx.fillRect(x,y,this.width,this.height);
ctx.restore();
}
//The player move method.
player.move=function(dir){
//Firstly remove it.Then show the new one.
this.miss();
switch(dir){
case "up":
this.position.y-=this.step;
break;
case "down":
this.position.y+=this.step;
break;
case "left":
this.position.x-=this.step;
break;
case "right":
this.position.x+=this.step;
break;
}
this.display(this.position.x,this.position.y);
}
//The player remove
player.miss=function(){
ctx.clearRect(this.position.x,this.position.y,this.width,this.height);
}
//display player
player.display((canWidth-player.width)/2,canHeight-player.height);
//add window keypress event listener
//keypress event will trigger the function every 33 millisecond.
//I do not know, whether it is 33 millisecond in other browser and Java Swing.
window.addEventListener("keypress",function(e){
var keyCode=e.keyCode;
if(keyCode===119){
//w
dir="up";
}else if(keyCode===100){
//d
dir="right";
}else if(keyCode===115){
//s
dir="down";
}else if(keyCode===97){
//a
dir="left";
}
//pass the dir to move the player.
player.move(dir);
});
</script>
</body>
</html>