<canvas id="canvas" width="400" height="400"></canvas>
// 创建画球函数
function Ball() {
  this.x = 30;
  this.y = 30;
  this.radius = 30;
  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();
  }
}

// requestAnimationFrame的兼容性写法
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame    ||
    window.oRequestAnimationFrame      ||
    window.msRequestAnimationFrame     ||
    function( callback ){
    window.setTimeout(callback, 1000 / 60);
  };
})();

window.cancelAnimationFrame = (function () {
  return window.cancelAnimationFrame ||
    window.webkitCancelAnimationFrame ||
    window.mozCancelAnimationFrame ||
    window.oCancelAnimationFrame ||
    function (timer) {
    window.clearTimeout(timer);
  };
})();


var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    ball = new Ball(),
    easing = 0.01;

// 初始化颜色变量
var red = 255,
    green = 0,
    blue = 0,
    redTarget = 0,
    greenTarget = 0,
    blueTarget = 255;

ball.fillStyle = "rgb(" + red +"," + green + "," + blue + ")";

// 缓动动画函数
var animRequest = null;
drawFrame();
function drawFrame() {
  animRequest = window.requestAnimationFrame(drawFrame, canvas);
  // 使用缓动动画
  red += Math.ceil((redTarget - red) * easing);
  green += Math.ceil((greenTarget - green) * easing);
  blue += Math.ceil((blueTarget - blue) * easing);

  // 最后把这三个单色值合并成一个颜色
  ball.fillStyle = "rgb(" + red +"," + green + "," + blue + ")";

  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.