煙花效果如下(請使用支持HTML5的浏覽器查看):
也可以點擊這裡查看效果:http:///keleyi/phtml/html5/14.htm
源代碼如下:
<style>canvas{background-color:#000000;;z-index:9999;}</style>
<canvas id="canvas-keleyi-com"></canvas>
<script>
var c = document.getElementById('canvas-ke'+'leyi-com');
if (!c.getContext) alert('請使用支持HTML5的浏覽器,例如Chrome,IE9以上。');
else(function(c, cvs) {
//隨著窗口調整畫布大小
var W, H;
var up = 0;
//(onresize = function() {
// c.width = W = window.innerWidth;
// c.height = H = window.innerHeight;
// })();
c.width=W=616;
c.height=H=400;
//生成一個煙花
function createPT(x, y, r, g, b) {
return {
r: r,g: g,b: b,
x: x,y: y,
//軌跡序列
pl: [],
dx: rnd(20) - 10,
dy: rnd(10) - 7,
life: 30 + rnd(30),
//移動函數,修改加速度和坐標
move: function() {
this.dx *= .98;
this.dy *= .98;
this.dy += .22;
this.x += this.dx;
this.y += this.dy;
this.pl.push([this.x, this.y]);
//保持軌跡長度
if (this.pl.length > 10) this.pl.shift();
this.life--;
}
};
}
//總煙火數組
var B = [];
//在x,y位置創建一個煙火
function createBoom(x, y) {
var q = [],
r = rnd(255) | 0,
g = rnd(255) | 0,
b = rnd(255) | 0;
for (var i = 0; i < rnd(16) + 15; i++) q.push(createPT(x, y, r, g, b));
B.push(q);
}
setInterval(function() {
cvs.clearRect(0, 0, W, H);
//依次繪制煙火
for (var n = 0; n < B.length; n++) {
var q = B[n];
for (var i = 0; i < q.length; i++) {
var pt = q[i];
pt.move();
dq(pt.pl, pt.life / 30, pt.r, pt.g, pt.b);
//超過生存周期就消失 柯 樂 義
if (pt.life <= 0) q.splice(i, 1);
}
//當一個煙火包含的煙花個數為零,則消滅這個煙火
if (!B[n].length) B.splice(n, 1);
}
//每隔一段時間添加一個新煙火
if (new Date - up < 2000 + rnd(2000)) return;
up = new Date;
createBoom(rnd(W / 2) + W / 4, rnd(50) + 50);
},20);
function rnd(n) {
return (n || 1) * Math.random();
}
function dq(ar, z, r, g, b) {
cvs.save();
//繪制軌跡。思路是每次都繪制一條透明的軌跡,疊加起來形成一條漸變的樣子
for (var i = 0; i < ar.length; i++) {
cvs.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + Math.abs(.2 * z) + ')';
cvs.lineWidth = Math.min(i + 1, 4)*2;
cvs.beginPath();
cvs.moveTo(ar[i][0], ar[i][1]);
for (var j = i + 1; j < ar.length; j++) cvs.lineTo(ar[j][0], ar[j][1]);
cvs.stroke();
}
cvs.restore();
}
})(c, c.getContext('2d'));</script>