用javascript写一个烟花
时间: 2023-02-06 11:51:38 浏览: 70
好的,这是一个使用 JavaScript 制作烟花的简单例子:
```
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置画布的大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 定义烟花对象
function Firework() {
// 随机设置烟花的起始位置
this.x = Math.random() * canvas.width;
this.y = canvas.height;
// 随机设置烟花的颜色
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
// 设置烟花的半径
this.radius = Math.random() * 4 + 1;
// 随机设置烟花的上升速度
this.vy = Math.random() * -3 - 4;
}
// 在画布上绘制烟花
Firework.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
};
// 更新烟花的位置
Firework.prototype.update = function() {
this.y += this.vy;
};
// 创建烟花数组
const fireworks = [];
// 定义绘制函数
function draw() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 遍历所有烟花
for (let i = 0; i < fireworks.length; i++) {
fireworks[i].draw();
fireworks[i].update();
// 如果烟花移出了画布,就将其从数组中删除
if (fireworks[i].y < 0) {
fireworks.splice(i, 1);
i--;
}
}
// 使用 requestAnimationFrame 递归调用 draw 函数,以便在浏览器刷新时继续绘制
requestAnimationFrame(draw);
}
// 使用 setInterval 定时生成新的烟花
setInterval(function() {
fireworks.push