使用canvas制作一个烟花的动画效果

创建一个烟花动画效果在前端开发中是一个相对复杂的任务,因为它涉及到许多数学和物理概念,如重力、速度和加速度。以下是一个简单的烟花动画效果的示例代码,使用HTML5的<canvas>元素和JavaScript。

  1. HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>烟花动画</title>
    <style>
        body, canvas {
            margin: 0;
            padding: 0;
            overflow: hidden;
            width: 100%;
            height: 100%;
            position: absolute;
        }
    </style>
</head>
<body>
    <canvas id="fireworksCanvas"></canvas>
    <script src="fireworks.js"></script>
</body>
</html>
  1. JavaScript (fireworks.js):
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

class Particle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.size = Math.random() * 5 + 1;
        this.speedX = Math.random() * 6 - 3;
        this.speedY = Math.random() * 6 - 3;
        this.gravity = 0.1;
        this.alpha = Math.random();
    }

    update() {
        this.speedY += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY;
        this.alpha -= 0.005;
    }

    draw() {
        ctx.globalAlpha = this.alpha;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.closePath();
        ctx.fillStyle = 'rgba(255, 100, 0, ' + this.alpha + ')';
        ctx.fill();
    }
}

let particles = [];

function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    if (Math.random() < 0.02) {
        particles.push(new Particle(canvas.width / 2, canvas.height));
    }
    for (let i = particles.length - 1; i >= 0; i--) {
        particles[i].update();
        particles[i].draw();
        if (particles[i].alpha < 0) {
            particles.splice(i, 1);
        }
    }
}

animate();

这个示例创建了一个简单的烟花效果,其中粒子从屏幕底部中心随机发射,并受到重力的影响。你可以根据需要调整粒子的数量、速度、大小和颜色等属性来定制效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王铁柱666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值