canvas实现简单的气泡特效

0.效果预览

ex.gif

1.完整代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>气泡效果</title>
    </head>
    <body>
        <canvas></canvas>
    </body>
    <script>
        class Circle{
            constructor(color, radius, v, angle, x, y){
                this.color = color;
                this.radius = radius;
                this.v = v;
                this.angle = angle;
                this.x = x;
                this.y = y;
            }
            
            draw(ctx){
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
                ctx.closePath();
                ctx.fillStyle = this.color;
                ctx.fill();
            }
        }

        function rColor(){
            let r = 255*Math.random();
            let g = 255*Math.random();
            let b = 255*Math.random();
            let o = Math.random();
            return 'rgba(' + r + ','+ g + ','+ b + ','+ o + ')';
        }

        function draw(){
            ctx.clearRect(0,0,canvas.width,canvas.height);
            for(let i=0; i<NUM; i++){
                arr[i].x += arr[i].v*Math.cos(arr[i].angle);
                arr[i].y += arr[i].v*Math.sin(arr[i].angle);
                arr[i].draw(ctx);
            }
            setTimeout(draw, 50);
        }

        let arr = [];
        const NUM = 1000;
        let centerX, centerY;
        const canvas = document.querySelector('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        centerX = canvas.width/2;
        centerY = canvas.height/2;
        for(let i=0; i<NUM; i++){
            arr.push(new Circle(rColor(),10*Math.random()+1,5*Math.random()+1,360*Math.random(),centerX,centerY));
        }
        
        draw();
    </script>
</html>

欢迎讨论。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容