利用javascript实现绘制2023新年烟花的示例代码
时间: 2023-12-26 13:01:57 浏览: 51
可以通过以下的Javascript示例代码实现绘制2023新年烟花的效果:
```javascript
// 获取画布元素
const canvas = document.getElementById('fireworks');
const ctx = canvas.getContext('2d');
// 设置画布大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 创建烟花粒子
class Firework {
constructor() {
this.x = Math.random() * canvas.width;
this.y = canvas.height;
this.speed = Math.random() * 5 + 1;
this.radius = Math.random() * 3 + 1;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.angle = Math.random() * Math.PI * 2;
this.velocity = {
x: Math.cos(this.angle) * this.speed,
y: Math.sin(this.angle) * this.speed
};
}
update() {
this.x += this.velocity.x;
this.y += this.velocity.y;
this.radius -= 0.02;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
// 创建烟花集合
const fireworks = [];
// 绘制烟花
function drawFireworks() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < fireworks.length; i++) {
fireworks[i].draw();
fireworks[i].update();
if (fireworks[i].radius <= 0) {
fireworks.splice(i, 1);
}
}
requestAnimationFrame(drawFireworks);
}
// 鼠标点击事件
canvas.addEventListener('click', (event) => {
const firework = new Firework();
fireworks.push(firework);
});
// 初始化绘制
drawFireworks();
```
以上代码利用Canvas和requestAnimationFrame方法实现了一个简单的烟花效果,每次点击鼠标会触发一次绽放,通过不断更新粒子的位置和半径,在黑色背景上实现烟花的飞溅效果。可以将以上代码嵌入到HTML文件中,通过浏览器打开即可看到2023新年烟花的绘制效果。