<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<title>让熊动起来</title>
<script type="text/javascript">
var backgroundImg=new Image();
var mushroomImg=new Image();
//定义一个熊
var bearEyesClosedImg=new Image();
var speed=2;//开始的速度
var horizontalSpeed=speed;//水平速度
var verticalSpeed=-speed;//垂直速度
var bearAngle=2;//熊旋转速度
var ctx;
var screenWidth;
var screenHeight;
//定义游戏物体对象
function GameObject(){
this.x=0;
this.y=0;
this.image=null;
}
function Mushroom(){};
Mushroom.prototype=new GameObject();//继承GameObject
//定义一个熊Amimal继承GameObject
function Animal(){};
Animal.prototype=new GameObject();
Animal.prototype.angle=0;//动物的角度,目前中(即作为动物它在屏幕上旋转退回)
var animal=new Animal();//实例化一个熊
var mushroom=new Mushroom();
function gameLoop(){
//清屏
ctx.clearRect(0, 0, screenWidth, screenHeight);
ctx.save();
//绘制背景
ctx.drawImage(backgroundImg,0,0);
//绘制蘑菇
ctx.drawImage(mushroom.image,mushroom.x,mushroom.y);
animal.x+=horizontalSpeed;
animal.y+=verticalSpeed;
animal.angle+=bearAngle;
ctx.translate(animal.x+(animal.image.width/2),animal.y+(animal.image.height/2));
ctx.rotate(animal.angle*Math.PI/180);
ctx.drawImage(animal.image,-(animal.image.width/2),-(animal.image.height/2));
ctx.restore();
}
function loadImages(){
mushroomImg.src="mushroom.png";
backgroundImg.src="forest1.jpg";
bearEyesClosedImg.src="bear_eyesclosed.png";
mushroom.image=mushroomImg;
animal.image=bearEyesClosedImg;
}
function AddEventHandlers(){
$("#container").mousemove(function(e){
mushroom.x=e.pageX-(mushroom.image.width/2);
});
}
$(window).ready(function(){
AddEventHandlers();
loadImages();
ctx=document.getElementById("canvas").getContext('2d');;
screenWidth=parseInt($("#canvas").attr("width"));
screenHeight = parseInt($("#canvas").attr("height"));
mushroom.image = mushroomImg;
mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
mushroom.y = screenHeight - 40;//蘑菇Y坐标
animal.x = parseInt(screenWidth/2);// 蘑菇X坐标
animal.y = screenHeight - 40;//蘑菇Y坐标
setInterval(gameLoop, 10);
});
</script>
</head>
<body>
<div id="container" style="border:1px solid; cursor:none; width:480px; height:320px;">
<canvas id="canvas" width="480" height="320" >
</canvas>
</div>
</body>
</html>