前端开发whqet,csdn,王海庆,whqet,前端开发专家
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
==== 炫彩logo粒子1==== ==全屏预览== ==在线编辑== ==下载收藏== ==援助投票==
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
<canvas id='c'></canvas>
html,body {
height: 100%;
}
body {
background: black;
overflow: hidden;
}
canvas {
max-width: 100%;
}
//数据存储,Base64图片信息,太长了占屏太多,请用力往下拉。
var picUrl = "data:image/png;base64,……";
//canvas基础设置
var canvas = document.getElementById("c"),ctx = canvas.getContext("2d"),w = canvas.width = window.innerWidth,h = canvas.height = window.innerHeight,logoParticles = [],particleIndex = 0,logo = new Image(),hue = 0;
//设置图象
logo.src = picUrl;
//加载完成后,获得图象像素,将粒子绑定在图象像素上
logo.onload = function() {
var posX = (w - this.width) / 2,posY = (h - this.height) / 2;
//绘制图形
ctx.drawImage(this,posX,posY);
//获得像素点
var imgData = ctx.getImageData(0,w,h),pixels = imgData.data;
//遍历像素点,绑定粒子
for (var y = 0; y < imgData.height; y += 3) {
for (var x = 0; x < imgData.width; x += 3) {
var alpha = pixels[((imgData.width * y) + x) * 4 + 3];
if (alpha > 0) {
logoParticles.push(new Particle(x,y));
}
}
}
//调用动画
animate();
};
//requesetAnimationFrame的方式设置动画
function animate() {
//调用polyfill
requestAnimationFrame(animate);
//本案例动画
ctx.fillStyle = "rgba(0,.1)";
ctx.fillRect(0,h);
for (var i in logoParticles) {
logoParticles[i].draw();
}
hue += 1;
}
//粒子类定义
function Particle(x,y) {
this.origX = this.x = x;
this.origY = this.y = y;
this.color = "white";
this.maxLife = this.random(20);
this.life = 0;
this.vx = this.random(⑴,1);
this.vy = this.random(⑴,1);
this.grav = .04;
this.index = particleIndex;
logoParticles[particleIndex] = this;
particleIndex++;
}
//粒子原型,draw、update、reset、random方法
Particle.prototype = {
constructor: Particle,//绘制
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,1,1);
this.update();
},//动画
update: function() {
if (this.life >= this.maxLife) {
logoParticles[this.index].reset();
}
this.x += this.vx;
this.y += this.vy;
this.vy += this.grav;
this.life++;
},//重置
reset: function() {
this.x = this.origX;
this.y = this.origY;
this.life = 0;
this.color = "hsl(" + hue + ",100%,50%)";
this.vx = this.random(⑴,1);
this.vy = this.random(⑴,1);
},//取随机数
random: function() {
var min = arguments.length == 1 ? 0 : arguments[0],max = arguments.length == 1 ? arguments[0] : arguments[1];
return Math.random() * (max - min) + min;
}
};