动画-向右移动

1.动画一

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        canvas {
            border: 1px solid #f00;
        }
    </style>
    <script type="text/javascript">
        window.requestAnimFrame = (function (callback) {
            return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function (callback) {
                window.setTimeout(callback, 1000 / 60);
            };
        })();
        function animate(lastTime, myRectangle) {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            // 更新图像
            var date = new Date();
            var time = date.getTime();
            var timeDiff = time - lastTime;
            var linearSpeed = 100; // 像素 / 秒
            var linearDistEachFrame = linearSpeed * timeDiff / 1000;
            var currentX = myRectangle.x;
            if (currentX < canvas.width - myRectangle.width -
            myRectangle.borderWidth / 2) {
                var newX = currentX + linearDistEachFrame;
                myRectangle.x = newX;
            }
            lastTime = time;
            // 清屏
            context.clearRect(0, 0, canvas.width, canvas.height);
            // 绘图
            context.beginPath();
            context.rect(myRectangle.x, myRectangle.y, myRectangle.width,
            myRectangle.height);
            context.fillStyle = "#8ED6FF";
            context.fill();
            context.lineWidth = myRectangle.borderWidth;
            context.strokeStyle = "black";
            context.stroke();
            // 请求绘制下一帧
            requestAnimFrame(function () {
                animate(lastTime, myRectangle);
            });
        }
        window.onload = function () {
            var myRectangle = {
                x: 0,
                y: 50,
                width: 100,
                height: 50,
                borderWidth: 5
            };
            var date = new Date();
            var time = date.getTime();
            animate(time, myRectangle);
        };
    </script>
</head>
<body>
    <canvas id="myCanvas" width="500" height="500" />
</body>
</html>

  

posted @ 2012-11-20 16:21  bradleydan  阅读(140)  评论(0)    收藏  举报