HTML5动态散花源码

以下是一个HTML5动态散花的示例代码:

<!DOCTYPE html>
<html>
<head>
    <title>HTML5动态散花</title>
    <style>
        body {
      
      
            margin: 0;
            padding: 0;
            background-color: #000;
        }
        canvas {
      
      
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        var ctx = canvas.getContext("2d");
        var particles = [];
        var particleCount = 300;
        for(var i=0; i<particleCount; i++) {
      
      
            particles.push(new particle());
        }
        function particle() {
      
      
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height;
            this.vx = Math.random() * 20 - 10;
            this.vy = Math.random() * 20 - 10;
            this.gravity = 0.4;
            this.radius = Math.random() * 20 + 10;
            this.color = "rgb("+parseInt(Math.random()*255, 10)+","+parseInt(Math.random()*255, 10)+","+parseInt(Math.random()*255, 10)+")";
            this.alpha = 1;
            this.draw = function() {
      
      
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
                ctx.fillStyle = this.color;
                ctx.globalAlpha = this.alpha;
                ctx.fill();
            }
        }
        function draw() {
      
      
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            for(var i=0; i<particles.length; i++) {
      
      
                particles[i].vy += particles[i].gravity;
                particles[i].x += particles[i].vx;
                particles[i].y += particles[i].vy;
                particles[i].alpha -= 0.01;
                if(particles[i].alpha < 0) {
      
      
                    particles.splice(i, 1);
                    i--;
                } else {
      
      
                    particles[i].draw();
                }
            }
            requestAnimationFrame(draw);
        }
        requestAnimationFrame(draw);
    </script>
</body>
</html>

该示例使用了HTML5的canvas元素和JavaScript来创建一个动态散花效果。CSS样式用于设置页面的背景颜色。JavaScript代码用于创建粒子对象,包括粒子的位置,速度,重力,半径,颜色和透明度,并且通过draw方法画出粒子。draw函数用于清空画布,更新粒子的位置,速度和透明度,并且画出所有粒子。通过requestAnimationFrame函数来实现动态效果。

动态散花效果

动态散花

猜你喜欢

转载自blog.csdn.net/dica54dica/article/details/129977542