您的位置:首页 > 其它

在Sprite 基础之上创建一个既可以控制移动,也可以动画的对象定义。

2012-07-06 14:00 676 查看
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var DHTMLSprite =function(params)
{
var width=params.width,
height=params.height,
imagesWidth=params.imagesWidth,
$element=params.$drawTarget.append("<div/>").find(':last'),
elementStyle=$element[0].style,
mathFloor=Math.floor;
$element.css({
position:'absolute',
width:width,
height:height,
backgroundImage:'url('+params.images+')'
});
var that={
draw:function(x,y){
elementStyle.left=x+'px';
elementStyle.top=y+'px';
return this;
},
changeImage:function(index){
index *=width;
var vOffset=-mathFloor(index/imagesWidth)*height;
var hOffset=-index%imagesWidth;
elementStyle.backgroundPosition=hOffset+'px '+vOffset+'px';
return this;
},
show:function(){
elementStyle.display='block';
return this;
},
hide:function(){
elementStyle.display='none';
return this;
},
destory:function(){
$element.remove();
}
}
return that;
}

var bouncySprite=function(params){
var x=params.x,
y=params.y,
xDir=params.xDir,
yDir=params.yDir,
maxX=params.maxX,
maxY=params.maxY,
animIndex=0,
that = DHTMLSprite(params);
that.moveAndDraw=function(){
x+=xDir;
y+=yDir;
animIndex+=xDir>0?1:-1;
animIndex %=5;
animIndex+=animIndex<0?5:0;
if((xDir<0&&x<0)||(xDir>0&&x>=maxX))
{
xDir=-xDir;
}
if((yDir<0&&y<0)||(yDir>0&&y>=maxY))
{
yDir=-yDir;
}
that.changeImage(animIndex);
that.draw(x,y);
return that;
}
return that;
}

var img =bouncySprite ({x:0,y:0,xDir:5,yDir:5,maxX:300,maxY:100, width:80,height:80,imagesWidth:330,$drawTarget:$("#group_nav"),images:'http://1812.img.pp.sohu.com.cn/images/2012/7/6/9/26/e33569437_1391c97fcacg213_b.jpg'}).show();
setInterval(function(){ img.moveAndDraw();},20);
});
</script>
<body>
<div id="group_nav"></div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐