日期:2014-05-17  浏览次数:20559 次

html5 实现动画(二)
<canvas id="canvas2" width="250" height="300" style="background-color:black">
    你的浏览器不支持 Canvas 标签,请使用 Chrome 浏览器 或者 FireFox 浏览器
</canvas><br/>
<input type="button" value="开始" onclick="move_box2()"/>
<input type="button" value="暂停" onclick="stop()"/>
<script type="text/javascript">
    //定时器
    var interval=null;
    //停止动画
    function stop(){
        clearInterval(interval);
    }
    //===================================================================
    //重新组织代码
    //====================================================================
    //方块的构造函数
    function Box(color,x,y,w,h,delta){
        this.color=color;
        this.x=x;
        this.y=y;
        this.w=w;
        this.h=h;
        this.delta=delta;
        //三十帧
        this.fps=30;
        //每一帧的延迟时间
        this.delay=1000/this.fps;
        //上一次重绘的时间
        this.last_update=0;
    }
    //方块更新
    Box.prototype.update=function(canvas){
        //获取当前时间
        var now=(new Date()).getTime();
        //如果达到了延迟时间,则更新数据
        if((now-this.last_update)>this.delay){
            //改变 y 坐标
            this.y=this.y+this.delta;
            //上边缘检测
            if(this.y<0){
                this.y=0;
                this.delta=-this.delta;
            }
            //下边缘检测
            if((this.y+this.h)>canvas.getAttribute("height")){
                this.y=canvas.getAttribute("height")-this.h;
                this.delta=-this.delta;
            }
            //记下最新一次绘制时间
            this.last_update=now;
        }
    }
    function move_box2(){
        //停止动画
        stop();
        //画布对象
        var canvas=document.getElementById("canvas2")
        //获取上下文对象
        var ctx = canvas.getContext("2d");
 &n