超级玛丽HTML5源代码学习------(五)

今天主要学习 step3-2.html   这里没有什么可说的,主要实现的就是  玩家角色 的移动,区别于step3-1.html的玩家原地移动

这里主要讲解  prototype 属性(原型)


下面的文章是转载的,原文地址:http://www.cnblogs.com/yjf512/archive/2011/06/03/2071914.html

JS中的phototype是JS中比较难理解的一个部分 

本文基于下面几个知识点: 

1 原型法设计模式

在.Net中可以使用clone()来实现原型法

原型法的主要思想是,现在有1个类A,我想要创建一个类B,这个类是以A为原型的,并且能进行扩展。我们称B的原型为A。 

2 javascript的方法可以分为三类:

a 类方法

b 对象方法

c 原型方法

例子:

function People(name)
{
  this.name=name;
  //对象方法
  this.Introduce=function(){
    alert("My name is "+this.name);
  }
}
//类方法
People.Run=function(){
  alert("I can run");
}
//原型方法
People.prototype.IntroduceChinese=function(){
  alert("我的名字是"+this.name);
}

 

//测试

var p1=new People("Windking");

p1.Introduce();

People.Run();

p1.IntroduceChinese();

这里主要注意  对象方法,类方法,原型方法的写法和申明

3 obj1.func.call(obj)方法

意思是将obj看成obj1,调用func方法

这里要对obj1和obj分清楚是什么,一般来说,obj 不需要注意,但是obj1需要注意了:

如果obj1是类,那么就是obj调用obj1的类方法;

如果obj1是实例,那么就是obj调用obj1的对象方法;


好了,下面一个一个问题解决: 

prototype是什么含义? 

javascript中的每个对象都有prototype属性,Javascript中对象的prototype属性的解释是:返回对象类型原型的引用。

A.prototype = new B();

理解prototype不应把它和继承混淆。A的prototype为B的一个实例,可以理解A将B中的方法和属性全部克隆了一遍。A能使用B的方法和属性。这里强调的是克隆而不是继承。可以出现这种情况:A的prototype是B的实例,同时B的prototype也是A的实例。

先看一个实验的例子

function baseClass()
{
  this.showMsg = function()
  {
     alert("baseClass::showMsg");   
  }
}

function extendClass()
{
}

extendClass.prototype = new baseClass();
var instance = new extendClass();
instance.showMsg(); // 显示baseClass::showMsg

我们首先定义了baseClass类,然后我们要定义extentClass,但是我们打算以baseClass的一个实例为原型,来克隆的extendClass也同时包含showMsg这个对象方法。

extendClass.prototype = new baseClass()就可以阅读为:extendClass是以baseClass的一个实例为原型克隆创建的。

那么就会有一个问题, 如果extendClass中本身包含有一个与baseClass的方法同名的方法会怎么样?

下面是扩展实验2:

function baseClass()
{
    this.showMsg = function()
    {
        alert("baseClass::showMsg");   
    }
}

function extendClass()
{
    this.showMsg =function ()
    {
        alert("extendClass::showMsg");
    }
}

extendClass.prototype = new baseClass();
var instance = new extendClass();

instance.showMsg();//显示extendClass::showMsg

实验证明:函数运行时会先去本体的函数中去找,如果找到则运行,找不到则去prototype中寻找函数。或者可以理解为prototype不会克隆同名函数。

 那么又会有一个新的问题:

如果我想使用extendClass的一个实例instance调用baseClass的对象方法showMsg怎么办? 

答案是可以使用call:

extendClass.prototype = new baseClass();
var instance = new extendClass();


var baseinstance = new baseClass();
baseinstance.showMsg.call(instance);//显示baseClass::showMsg

这里的baseinstance.showMsg.call(instance);阅读为“将instance当做baseinstance来调用,调用它的对象方法showMsg”

好了,这里可能有人会问,为什么不用baseClass.showMsg.call(instance);

这就是对象方法和类方法的区别,我们想调用的是baseClass的对象方法 

最后,下面这个代码如果理解清晰,那么这篇文章说的就已经理解了:

<script type="text/javascript">

function baseClass()
{
    this.showMsg = function()
    {
        alert("baseClass::showMsg");   
    }
   
    this.baseShowMsg = function()
    {
        alert("baseClass::baseShowMsg");
    }
}
baseClass.showMsg = function()
{
    alert("baseClass::showMsg static");
}

function extendClass()
{
    this.showMsg =function ()
    {
        alert("extendClass::showMsg");
    }
}
extendClass.showMsg = function()
{
    alert("extendClass::showMsg static")
}

extendClass.prototype = new baseClass();
var instance = new extendClass();

instance.showMsg(); //显示extendClass::showMsg
instance.baseShowMsg(); //显示baseClass::baseShowMsg
instance.showMsg(); //显示extendClass::showMsg

baseClass.showMsg.call(instance);//显示baseClass::showMsg static

var baseinstance = new baseClass();
baseinstance.showMsg.call(instance);//显示baseClass::showMsg

</script>

至此,prototype 属性基本掌握了,下面来看看在step3-2.thml中的代码:

Animation.prototype={
	constructor :Animation ,

	// Animation 包含的Frame, 类型:数组
	frames : null,
	// 包含的Frame数目
	frameCount : -1 ,
	// 所使用的图片id(在ImgCache中存放的Key), 字符串类型. 
	img : null,
	currentFrame : null ,
	currentFrameIndex : -1 ,
	currentFramePlayed : -1 ,
	
	// 初始化Animation
	init : function(){
		// 根据id取得Image对象
		this.img = ImgCache[this.img]||this.img;
		
		this.frames=this.frames||[];
		this.frameCount = this.frames.length;
		
		// 缺省从第0帧播放
		this.setFrame(0);
	},
	
	//设置当前帧
	setFrame : function(index){
		this.currentFrameIndex=index;
		this.currentFrame=this.frames[index];
		this.currentFramePlayed=0;	
	},
	
	// 更新Animation状态. deltaTime表示时间的变化量.
	update : function(deltaTime){
		//判断当前Frame是否已经播放完成, 
		if (this.currentFramePlayed>=this.currentFrame.duration){
			//播放下一帧
			
			if (this.currentFrameIndex >= this.frameCount-1){
				//当前是最后一帧,则播放第0帧
				this.currentFrameIndex=0;
			}else{
				//播放下一帧
				this.currentFrameIndex++;
			}
			//设置当前帧信息
			this.setFrame(this.currentFrameIndex);
		
		}else{
			//增加当前帧的已播放时间.
			this.currentFramePlayed += deltaTime;
		}
	},
	
	//绘制Animation
	draw : function(gc,x,y){
		// gc 是能够绘制图像的对象,一般是下面被context传递
		var f=this.currentFrame;
		gc.drawImage(this.img, f.x , f.y, f.w, f.h , x, y, f.w, f.h );
	}
};

它的模型就是这样的: A.prototype = {};{}里面就是一个对象具有的各种属性和方法,使用了prototype,使得Animation也具有

{}里面的属性和方法。

所以,当我们创建一个 Animation 实例的时候我们就可以调用draw方法,update方法,setFrame方法,init方法,这些调用都在startDemo方法中调用

// Demo的启动函数
function startDemo(){
	
	// 一些简单的初始化, 
	var FPS=30;
	var sleep=Math.floor(1000/FPS);

	//初始坐标
	var x=0, y=284;	
	//移动速度 . speedY<0,向上移动.
	var speedX = 65/1000 , speedY=-45/1000 ;
	//x/y坐标的最大值和最小值, 可用来限定移动范围.
	var minX=0, maxX=500, minY=0, maxY=284;
	
	// 创建一个Animation对象
	var animation = new Animation({
		img : "player" ,
		//该动画由3帧构成
		frames : [
			{x : 0, y : 0, w : 50, h : 60, duration : 100},
			{x : 50, y : 0, w : 50, h : 60, duration : 100},
			{x : 100, y : 0, w : 50, h : 60, duration : 100}
		]
	} );
	// 初始化Animation
	animation.init();
	
	//主循环
	var mainLoop=setInterval(function(){

		//距上一次执行相隔的时间.(时间变化量), 目前可近似看作sleep.
		var deltaTime=sleep;
		
		//每次循环,改变一下绘制的坐标. 
		x=x+speedX*deltaTime; //向右移动
		y=y+speedY*deltaTime; //向上移动, 坐标y减小,这点和数学中的坐标系不同.
		
		//限定移动范围
		x=Math.max(minX,Math.min(x,maxX));
		y=Math.max(minY,Math.min(y,maxY));
		
		// 更新Animation状态
		animation.update(deltaTime);
	
		//使用背景覆盖的方式 清空之前绘制的图片
		context.drawImage(ImgCache["bg"],0,0);
		
		//绘制Animation
		animation.draw(context, x,y);
		
	},sleep);

}

至此,step3及以前的都基本掌握了。下面附上step3-2.html的源代码:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Cache-Control" content="no-cache" />


<title>My first Game</title>

<style type="text/css">
body {
	border:none 0px;
	margin:0px;
	padding:10px;
	font-size : 16px;
	background-color : #f3f3f3;
}

canvas {
	border : 1px solid blue; 
}
</style>


<script type="text/javascript">

// 加载图片
function loadImage(srcList,callback){
	var imgs={};
	var totalCount=srcList.length;
	var loadedCount=0;
	for (var i=0;i<totalCount;i++){
		var img=srcList[i];
		var image=imgs[img.id]=new Image();		
		image.src=img.url;
		image.οnlοad=function(event){
			loadedCount++;
		}		
	}
	if (typeof callback=="function"){
		var Me=this;
		function check(){
			if (loadedCount>=totalCount){
				callback.apply(Me,arguments);
			}else{		
				setTimeout(check,100);
			}	
		}
		check();
	}
	return imgs;
}

//定义全局对象
var ImgCache=null;
var canvas=null;
var context=null;

// 页面初始化函数
function init(){
	
	// 创建canvas,并初始化 (我们也可以直接以标签形式写在页面中,然后通过id等方式取得canvas)
	canvas=document.createElement("canvas");
	canvas.width=600;
	canvas.height=400;
	document.body.appendChild(canvas);
		
	// 取得2d绘图上下文 
	context= canvas.getContext("2d");
	
	//加载图片,并存入全局变量 ImgCache, 
	// 加载完成后,调用startDemo
	ImgCache=loadImage( [ 
			{ 	id : "player",
				url : "../res/player.png"
			},
			{ 	id : "bg",
				url : "../res/bg.png"
			}
		], 
		startDemo );

}


// Animation类.
// cfg为Object类型的参数集, 其属性会覆盖Animation原型中定义的同名属性.
function Animation(cfg){
	for (var attr in cfg ){
		this[attr]=cfg[attr];
	}
}

Animation.prototype={
	constructor :Animation ,

	// Animation 包含的Frame, 类型:数组
	frames : null,
	// 包含的Frame数目
	frameCount : -1 ,
	// 所使用的图片id(在ImgCache中存放的Key), 字符串类型. 
	img : null,
	currentFrame : null ,
	currentFrameIndex : -1 ,
	currentFramePlayed : -1 ,
	
	// 初始化Animation
	init : function(){
		// 根据id取得Image对象
		this.img = ImgCache[this.img]||this.img;
		
		this.frames=this.frames||[];
		this.frameCount = this.frames.length;
		
		// 缺省从第0帧播放
		this.setFrame(0);
	},
	
	//设置当前帧
	setFrame : function(index){
		this.currentFrameIndex=index;
		this.currentFrame=this.frames[index];
		this.currentFramePlayed=0;	
	},
	
	// 更新Animation状态. deltaTime表示时间的变化量.
	update : function(deltaTime){
		//判断当前Frame是否已经播放完成, 
		if (this.currentFramePlayed>=this.currentFrame.duration){
			//播放下一帧
			
			if (this.currentFrameIndex >= this.frameCount-1){
				//当前是最后一帧,则播放第0帧
				this.currentFrameIndex=0;
			}else{
				//播放下一帧
				this.currentFrameIndex++;
			}
			//设置当前帧信息
			this.setFrame(this.currentFrameIndex);
		
		}else{
			//增加当前帧的已播放时间.
			this.currentFramePlayed += deltaTime;
		}
	},
	
	//绘制Animation
	draw : function(gc,x,y){
		// gc 是能够绘制图像的对象,一般是下面被context传递
		var f=this.currentFrame;
		gc.drawImage(this.img, f.x , f.y, f.w, f.h , x, y, f.w, f.h );
	}
};




// Demo的启动函数
function startDemo(){
	
	// 一些简单的初始化, 
	var FPS=30;
	var sleep=Math.floor(1000/FPS);

	//初始坐标
	var x=0, y=284;	
	//移动速度 . speedY<0,向上移动.
	var speedX = 65/1000 , speedY=-45/1000 ;
	//x/y坐标的最大值和最小值, 可用来限定移动范围.
	var minX=0, maxX=500, minY=0, maxY=284;
	
	// 创建一个Animation对象
	var animation = new Animation({
		img : "player" ,
		//该动画由3帧构成
		frames : [
			{x : 0, y : 0, w : 50, h : 60, duration : 100},
			{x : 50, y : 0, w : 50, h : 60, duration : 100},
			{x : 100, y : 0, w : 50, h : 60, duration : 100}
		]
	} );
	// 初始化Animation
	animation.init();
	
	//主循环
	var mainLoop=setInterval(function(){

		//距上一次执行相隔的时间.(时间变化量), 目前可近似看作sleep.
		var deltaTime=sleep;
		
		//每次循环,改变一下绘制的坐标. 
		x=x+speedX*deltaTime; //向右移动
		y=y+speedY*deltaTime; //向上移动, 坐标y减小,这点和数学中的坐标系不同.
		
		//限定移动范围
		x=Math.max(minX,Math.min(x,maxX));
		y=Math.max(minY,Math.min(y,maxY));
		
		// 更新Animation状态
		animation.update(deltaTime);
	
		//使用背景覆盖的方式 清空之前绘制的图片
		context.drawImage(ImgCache["bg"],0,0);
		
		//绘制Animation
		animation.draw(context, x,y);
		
	},sleep);

}



	
</script>

</head> 
<body οnlοad="init()"> 


<div align="center"><a href="http://www.linuxidc.com" target="_blank">www.Linuxidc.com</a></div>
</body>
</html>

若有不对的地方请及时告知,不甚感激!

转载请说明,交流请联系nlp30508@qq.com  

谢谢欣赏!




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值