效果如下
實現代碼如下:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>線性漸變動畫</title>
<style>
body{
width:100%;
overflow:hidden;
margin:0;
background: hsla(0,0%,0%,1);
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var c = document.getElementById('canvas'),
$ = c.getContext('2d'),
w = c.width = window.innerWidth, //設置 Canvas 寬度(全屏)
h = c.height = window.innerHeight, //設置 Canvas 高度(全屏)
t = 0, num = 450, //num = 450 繪製數量
u = 0, _u, //線性漸變的顏色值
s, a, b,
x, y, _x, _y,
_t = 1 / 100;
//控制擺動速度
var anim = function() {
$.globalCompositeOperation = 'source-over'; //默認,在目標圖像上顯示源圖像
$.fillStyle = 'hsla(0, 0%, 0%, .75)'; //填充顏色
$.fillRect(0, 0, w, h); //繪製“已填色”的矩形
$.globalCompositeOperation = 'lighter'; //顯示源圖像 + 目標圖像
for (var i = 0; i < 2; i++) {
x = 0; _u = (u / 4)+i;
$.beginPath();
//循環繪製個數(num),正玄 Math.sin(弧度),餘弦 Math.cos(弧度)
for (var j = 0; j < num; j++) {
x -= .72 * Math.sin(4);
y = x * Math.sin(i + 3.0 * t + x / 20) / 2;
_x = x * Math.cos(b) - y * Math.sin(b);
_y = x * Math.sin(b) + y * Math.cos(b);
b = (j * 3) * Math.PI / 6.8;
$.lineWidth = .18; //線條寬度
$.arc(w / 2 - _x, h / 2 -_y, .5, 0, 2 * Math.PI); //畫圓(半徑0.5)
}
//設置線性漸變
var g = $.createLinearGradient(w / 2 + _x, h / 2 + _y, 0, w / 2 + _x, h / 2 + _y);
g.addColorStop(0.0, 'hsla('+ u +',85%,50%,1)');
g.addColorStop(0.5, 'hsla('+ _u +',85%,40%,1)');
g.addColorStop(1, 'hsla(0,0%,5%,1)');
$.strokeStyle = g; //線條顏色為 g(線性漸變)
$.stroke();
}
t += _t; //擺動速度會不斷增加
u -= .2; //改變顏色值
window.requestAnimationFrame(anim); //繪製動畫 anim
};
anim();
//監聽,當瀏覽器寬度和高度改變時,改變 Canvas 的寬度和高度
window.addEventListener('resize', function() {
c.width = w = window.innerWidth;
c.height = h = window.innerHeight;
}, false);
</script>
</body>
</html>