帮我写一个放烟花的js代码
时间: 2023-03-24 13:04:04 浏览: 115
JS实现放烟花效果
当然可以!这是一个简单的放烟花的代码:
```
window.onload = function() {
// 创建一个画布
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
// 定义烟花的颜色
var colors = ["#f00", "#0f0", "#00f", "#ff0", "#f0f", "#0ff"];
// 定义烟花的粒子
function Firework(x, y) {
this.x = x;
this.y = y;
this.color = colors[Math.floor(Math.random() * colors.length)];
this.particles = [];
this.explode = function() {
// 生成烟花的粒子
for (var i = 0; i < 100; i++) {
var particle = new Particle(this.x, this.y, this.color);
this.particles.push(particle);
}
};
this.draw = function() {
// 绘制烟花的粒子
for (var i = 0; i < this.particles.length; i++) {
var particle = this.particles[i];
particle.move();
particle.draw();
}
};
}
// 定义烟花的粒子
function Particle(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.speed = {x: -2 + Math.random() * 4, y: -3 + Math.random() * 2};
this.move = function() {
// 更新粒子的位置
this.x += this.speed.x;
this.y += this.speed.y;
};
this.draw = function() {
// 绘制粒子
ctx.beginPath();
ctx.arc(this.x, this.y, 1, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
};
}
// 创建烟花
var fireworks = [];
setInterval(function() {
var x = Math.random() * canvas.width;
var y = canvas.height;
var firework = new Firework(x, y);
firework.explode();
fireworks.push(firework);
}, 1000);
// 动画循环
阅读全文