代码改变世界

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

2012-07-06 14:00  chris-shao  阅读(136)  评论(0编辑  收藏  举报
<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>