用 HTML5 的 canvas 元素和 JavaScript 实现烟花效果,包含代码部分
时间: 2023-03-31 16:03:59 浏览: 118
好的,我可以回答这个问题。以下是一个简单的 HTML5 canvas 和 JavaScript 实现烟花效果的示例代码:
HTML 代码:
```
<canvas id="fireworks"></canvas>
```
JavaScript 代码:
```
var canvas = document.getElementById("fireworks");
var ctx = canvas.getContext("2d");
var particles = [];
var numParticles = 100;
var colors = ["#FF000", "#00FF00", "#000FF", "#FFFF00", "#00FFFF", "#FF00FF"];
function Particle(x, y, radius, color, vx, vy, ax, ay) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.vx = vx;
this.vy = vy;
this.ax = ax;
this.ay = ay;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, , 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
}
Particle.prototype.update = function() {
this.vx += this.ax;
this.vy += this.ay;
this.x += this.vx;
this.y += this.vy;
this.radius -= .05;
}
function createParticles(x, y) {
for (var i = ; i < numParticles; i++) {
var radius = Math.random() * 5 + 2;
var color = colors[Math.floor(Math.random() * colors.length)];
var angle = Math.random() * Math.PI * 2;
var speed = Math.random() * 5 + 2;
var vx = Math.cos(angle) * speed;
var vy = Math.sin(angle) * speed;
var ax = ;
var ay = .1;
particles.push(new Particle(x, y, radius, color, vx, vy, ax, ay));
}
}
function animate() {
ctx.clearRect(, , canvas.width, canvas.height);
for (var i = ; i < particles.length; i++) {
particles[i].draw();
particles[i].update();
if (particles[i].radius <= ) {
particles.splice(i, 1);
}
}
requestAnimationFrame(animate);
}
canvas.addEventListener("click", function(event) {
createParticles(event.clientX, event.clientY);
});
animate();
```
这段代码创建了一个 canvas 元素,并在其中实现了一个烟花效果。当用户在 canvas 上点击时,会在点击位置创建一组粒子,这些粒子会以随机的颜色和速度向外扩散,并逐渐消失。这个效果通过创建一个 Particle 类来实现,每个粒子都是一个 Particle 的实例。在 animate 函数中,每个粒子都会被绘制和更新,同时过小的粒子会被从数组中删除。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)