//获取元素
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();
//随机函数
function rnd(min,max) {return parseInt(Math.random()*(max-min))+min;}
//装载粒子的数组
var partciles = [];
//创建粒子
function Dot(x,y) {
//抽样像素的坐标
this.x = x;
this.y = y;
//开始的随机位置
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;
//标记动画运行的次数
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() {
//更新坐标
this.count++;
if(this.count<=this.duration) {
this.startX += this.deltaX;
this.startY += this.deltaY;
}else {
cancelAnimationFrame(raf);
}
}
///////////////////////////////////////////////////////////////////////////
//获取canvas画布上的所有像素点
var pixels = ctx.getImageData(0,0,cw,ch);
for(var x=0;x
for (var y=0;y
//求当前点在pixels.data下的红色通道的下标
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;
//遍历装载粒子的数组
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);
效果
网友评论