借助CSS3 animation实现canvas颜色动画实例页面

回到相关文章 »

效果:

canvas色值动画

CSS3色值动画

代码:

CSS代码:
.shape.active {
    animation: color 3.33s both;    
}
@keyframes color {
    0% { background-color: red; }
    7% { background-color: orange; }
   17% { background-color: yellow; }
   22% { background-color: green; }
   42% { background-color: cyan; }
   82% { background-color: blue; }
   100% { background-color: purple; }    
}
                
HTML代码:
<canvas id="canvas"></canvas>
<div id="shape" class="shape active"></div>
                
JS代码:
// CSS3动画元素
var eleShape = document.getElementById('shape');
// Canvas元素
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var width = canvas.width, height = canvas.height;
// 绘制方法
var draw = function () {
    context.clearRect(0, 0, width, height);
    // 可以确定色值
    context.fillStyle = window.getComputedStyle(eleShape).backgroundColor;
    context.arc(width / 2, height / 2, height / 2, 0, 2 * Math.PI);
    context.fill();
    // 持续变化
    requestAnimationFrame(draw);
};
draw();