// js 烟花示例代码
// 创建一个烟花类
class Firework {
constructor(x, y, targetX, targetY) {
this.x = x;
this.y = y;
this.targetX = targetX;
this.targetY = targetY;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.particles = [];
}
// 更新烟花位置
update() {
this.x += (this.targetX - this.x) * 0.1;
this.y += (this.targetY - this.y) * 0.1;
if (Math.hypot(this.x - this.targetX, this.y - this.targetY) < 2) {
this.explode();
}
}
// 烟花爆炸效果
explode() {
for (let i = 0; i < 100; i++) {
this.particles.push(new Particle(this.targetX, this.targetY, this.color));
}
}
// 绘制烟花
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
for (let particle of this.particles) {
particle.update();
particle.draw(ctx);
}
}
}
// 创建一个粒子类
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.angle = Math.random() * Math.PI * 2;
this.speed = Math.random() * 5 + 2;
this.life = 1;
}
// 更新粒子位置
update() {
this.x += Math.cos(this.angle) * this.speed;
this.y += Math.sin(this.angle) * this.speed;
this.life -= 0.01;
}
// 绘制粒子
draw(ctx) {
if (this.life > 0) {
ctx.beginPath();
ctx.arc(this.x, this.y, 1, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.life;
ctx.fill();
}
}
}
// 初始化画布和烟花
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
const fireworks = [];
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.05) {
fireworks.push(new Firework(
Math.random() * canvas.width,
canvas.height,
Math.random() * canvas.width,
Math.random() * canvas.height / 2
));
}
for (let i = fireworks.length - 1; i >= 0; i--) {
fireworks[i].update();
fireworks[i].draw(ctx);
if (fireworks[i].particles.length === 0 && fireworks[i].x === fireworks[i].targetX && fireworks[i].y === fireworks[i].targetY) {
fireworks.splice(i, 1);
}
}
requestAnimationFrame(animate);
}
animate();
x
, y
) 和目标位置 (targetX
, targetY
)。烟花的颜色是随机生成的。这段代码会在网页上创建一个动态的烟花效果,每隔一段时间会随机生成一个新的烟花并爆炸成多个粒子。
上一篇:js 代码加密
下一篇:js 获取定位
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站