HTML5代碼可以實現(xiàn)許多精美的網站特效,其中最流行的之一就是粒子特效。粒子特效是指將許多小的點或圖形以不同動畫效果組合在一起形成各種形態(tài)的動態(tài)效果。下面是一個HTML5的粒子特效代碼。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Particle Effect</title>
<style>
#canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
particles = [],
amount = 0,
mouse = {x:0,y:0},
radius = 1;
var colors = ["rgb(70, 61, 61)", "rgb(115, 88, 88)", "rgb(147, 121, 121)", "rgb(181, 165, 165)", "rgb(212, 203, 203)"];
var copyCanvas = function(){
ctx.save();
ctx.fillStyle = "rgba(0,0,0,0.1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
}
var Particle = function(x, y){
this.x = x || Math.random()*canvas.width;
this.y = y || Math.random()*canvas.height;
this.radius = radius;
this.color = colors[Math.floor(Math.random()*colors.length)];
this.speedX = -1.5 + Math.random()*3;
this.speedY = -1.5 + Math.random()*3;
this.life = 30 + Math.random()*10;
};
Particle.prototype.draw = function(){
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
ctx.closePath();
ctx.fill();
};
var createParticles = function(){
if (mouse.x && mouse.y) {
for(var i=0;i<=5;i++) {
particles.push(new Particle(mouse.x, mouse.y));
}
amount += 5;
}
while (particles.length < amount){
particles.push(new Particle());
amount--;
}
}
var onMouseMove = function(e){
mouse.x = e.clientX - canvas.offsetLeft;
mouse.y = e.clientY - canvas.offsetTop;
}
var render = function(){
copyCanvas();
createParticles();
particles.forEach(function(particle){
particle.draw();
particle.x += particle.speedX;
particle.y += particle.speedY;
particle.life -= 1;
if (particle.life <= 0){
particles.splice(particles.indexOf(particle), 1);
}
});
}
canvas.addEventListener("mousemove", onMouseMove);
setInterval(render, 1000/60);
</script>
</body>
</html>
以上代碼中,創(chuàng)建了一個粒子類Particle,每個粒子有自己的屬性,如顏色、速度、壽命等。在render函數(shù)中,根據(jù)mouse.x和mouse.y的值不斷創(chuàng)建新的粒子,并且更新所有粒子的位置和狀態(tài)。最終效果是在鼠標移動時出現(xiàn)一些小球的運動軌跡。
上一篇時鐘羅盤css