用html写一个粒子特效
时间: 2023-09-26 21:07:35 浏览: 49
好的,以下是一个简单的粒子特效的HTML代码示例,使用Canvas和JavaScript实现:
```html
<!DOCTYPE html>
<html>
<head>
<title>粒子特效</title>
<style type="text/css">
canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script type="text/javascript">
// 获取画布对象
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 创建粒子对象
var particles = [];
for(var i=0; i<100; i++){
particles.push({
x: Math.random()*canvas.width,
y: Math.random()*canvas.height,
radius: Math.random()*5+1,
color: "rgb("+parseInt(Math.random()*255, 10)+","+parseInt(Math.random()*255, 10)+","+parseInt(Math.random()*255, 10)+")",
speedX: Math.random()*3-1.5,
speedY: Math.random()*3-1.5
});
}
// 绘制粒子
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(var i=0; i<particles.length; i++){
var p = particles[i];
ctx.beginPath();
ctx.arc(p.x, p.y, p.radius, 0, Math.PI*2, false);
ctx.fillStyle = p.color;
ctx.fill();
p.x += p.speedX;
p.y += p.speedY;
if(p.x < -50) p.x = canvas.width+50;
if(p.y < -50) p.y = canvas.height+50;
if(p.x > canvas.width+50) p.x = -50;
if(p.y > canvas.height+50) p.y = -50;
}
requestAnimationFrame(draw);
}
// 开始绘制
draw();
</script>
</body>
</html>
```
在这个示例中,我们创建了100个随机位置、大小、颜色、速度的粒子,在画布上绘制出来,并且让它们自动运动并且循环出现在画布的另一侧。你可以根据自己的需求,调整粒子的数量、大小、颜色、速度等参数,来实现不同的特效效果。