以下是一个在 HBuilder X 中实现动态烟花效果的代码示例:

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>动态烟花效果</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
        canvas {
            display: block;
        }
    </style>
</head>
<body>
    <canvas id='fireworks'></canvas>
    <script>
        // 创建烟花粒子对象
        function createFirework(x, y) {
            const firework = {};
            firework.x = x;
            firework.y = y;
            firework.angle = Math.random() * Math.PI * 2;
            firework.speed = Math.random() * 5 + 1;
            firework.radius = Math.random() * 3 + 1;
            firework.opacity = 1;
            firework.color = randomColor();

            return firework;
        }

        // 生成随机颜色
        function randomColor() {
            const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF'];
            return colors[Math.floor(Math.random() * colors.length)];
        }

        // 更新烟花粒子位置和状态
        function updateFirework(firework, index) {
            firework.x += Math.cos(firework.angle) * firework.speed;
            firework.y += Math.sin(firework.angle) * firework.speed;
            firework.opacity -= 0.01;

            if (firework.opacity <= 0) {
                fireworks.splice(index, 1);
            }
        }

        // 绘制烟花粒子
        function drawFirework(firework) {
            ctx.beginPath();
            ctx.arc(firework.x, firework.y, firework.radius, 0, Math.PI * 2);
            ctx.fillStyle = firework.color;
            ctx.globalAlpha = firework.opacity;
            ctx.fill();
        }

        // 创建画布和上下文
        const canvas = document.getElementById('fireworks');
        const ctx = canvas.getContext('2d');

        // 设置画布大小
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        // 存储烟花粒子的数组
        const fireworks = [];

        // 监听鼠标点击事件
        canvas.addEventListener('click', function(event) {
            const mouseX = event.clientX;
            const mouseY = event.clientY;

            for (let i = 0; i < 50; i++) {
                fireworks.push(createFirework(mouseX, mouseY));
            }
        });

        // 动画循环
        function animate() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            for (let i = 0; i < fireworks.length; i++) {
                const firework = fireworks[i];

                updateFirework(firework, i);
                drawFirework(firework);
            }

            requestAnimationFrame(animate);
        }

        animate();
    </script>
</body>
</html>

在上面的代码中,我们使用canvas元素来创建一个画布,并通过JavaScript代码实现了动态烟花效果。当鼠标点击画布时,会在点击位置生成一组烟花粒子,然后通过不断更新和绘制粒子的位置和状态来实现动画效果。


原文地址: https://www.cveoy.top/t/topic/fN0I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录