<canvas id="canvas" width="600" height="100"></canvas>
// requestAnimationFrame的兼容性写法
window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||
            function( callback ){
                window.setTimeout(callback, 1000 / 60);
            };
})();

// cancelAnimationFrame的兼容性写法
window.cancelAnimationFrame = (function () {
    return window.cancelAnimationFrame ||
            window.webkitCancelAnimationFrame ||
            window.mozCancelAnimationFrame ||
            window.oCancelAnimationFrame ||
            function (timer) {
                window.clearTimeout(timer);
            };
})();

// 创建画球函数
function Ball() {
    this.x = 0;
    this.y = 0;
    this.radius = 10;
    this.fillStyle = "#f85455";
    this.draw = function(cxt) {
        cxt.fillStyle = this.fillStyle;
        cxt.beginPath();
        cxt.arc(this.x, this.y, this.radius,  0, 2 * Math.PI, true);
        cxt.closePath();
        cxt.fill();
    }
}

var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        ball = new Ball(),
        spring = 0.1,
        targetX = canvas.width / 2,
        vx = 0;
ball.x = 20;
ball.y = 20;

// 缓动动画函数
var animRequest = null;
(function drawFrame() {
    animRequest = window.requestAnimationFrame(drawFrame, canvas);
    context.clearRect(0, 0, canvas.width, canvas.height);
    // 小球当前位置与目标点的距离
    var dx = targetX - ball.x;
    // 小球的加速度
    var ax = dx * spring;
    // 小球的速度
    vx += ax;
    // 计算出小球当前的位置
    ball.x += vx;
    ball.draw(context);
})();

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.