//獲取元素
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var cw = document.documentElement.clientWidth;
var ch = document.documentElement.clientHeight;
canvas.width = cw;
canvas.height = ch;
//初始的HTML5文本
ctx.save();
ctx.font = "300px 黑體";
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("小伍哥",cw/2,ch/2);
ctx.restore();
//隨機(jī)函數(shù)
function rnd(min,max) {return parseInt(Math.random()*(max-min))+min;}
//裝載粒子的數(shù)組
var partciles = [];
//創(chuàng)建粒子
function Dot(x,y) {
//抽樣像素的坐標(biāo)
this.x = x;
this.y = y;
//開始的隨機(jī)位置
this.startX = rnd(0,cw);
this.startY = rnd(0,ch);
//顏色
this.color = "rgb("+rnd(0,255)+","+rnd(0,255)+","+rnd(0,255)+")";
// this.color = "green";
//半徑
this.radius = 4;
//分多少步走完
this.duration = 50;
//標(biāo)記動(dòng)畫運(yùn)行的次數(shù)
this.count = 0;
//每次的增量
this.deltaX = (this.x - this.startX)/this.duration;
this.deltaY = (this.y - this.startY)/this.duration;
}
//繪制粒子
Dot.prototype.draw = function() {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.startX,this.startY,this.radius,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
ctx.restore();
}
//更新粒子
Dot.prototype.update = function() {
//更新坐標(biāo)
this.count++;
if(this.count<=this.duration) {
this.startX += this.deltaX;
this.startY += this.deltaY;
}else {
cancelAnimationFrame(raf);
}
}
///////////////////////////////////////////////////////////////////////////
//獲取canvas畫布上的所有像素點(diǎn)
var pixels = ctx.getImageData(0,0,cw,ch);
for(var x=0;x
for (var y=0;y
//求當(dāng)前點(diǎn)在pixels.data下的紅色通道的下標(biāo)
var pos = (y*pixels.width+x)*4;
if(pixels.data[pos+3]>128) {
var dot = new Dot(x,y);
partciles.push(dot);
}
}
}
///////////////////////////////////////////////////////////////////////////
//擦除畫布
canvas.width = canvas.width;
//遍歷裝載粒子的數(shù)組
for(var i in partciles) {
var dot = partciles[i];
ctx.beginPath();
ctx.fillStyle = dot.color;
ctx.arc(dot.startX,dot.startY,dot.radius,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
}
function change() {
canvas.width = canvas.width;
raf = requestAnimationFrame(change);
for(var i in partciles) {
var dot = partciles[i];
dot.draw();
dot.update();
}
}
var raf = requestAnimationFrame(change);
效果