0
点赞
收藏
分享

微信扫一扫

HTML使用canvas画布实现涟漪效果

王小沫 2022-04-16 阅读 74

js面向对象思想与canvas画布结合实现涟漪效果

先看效果图
在这里插入图片描述

相关代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            background-color: black;
        }
        #c1{
            background: white;
        }
        .wrap{
            width: 80vw;
            height: 80vh;
            text-align: center;
            margin: 20px auto;
        }
        button:hover,button:active{
            border: none;
            list-style: none;
        }
        button{
            border: none;
            width: 100px;
            height: 60px;
            border-radius: 12px;
            font-weight: bold;
            font-size: 20px;
            background-color: pink;
        }
        
    </style>
</head>
<body>
    <div class="wrap">
        <canvas id="c1" width="800" height="800"></canvas>
        <br>
        <button>开始</button>
        <button>结束</button>
    </div>

    <script>
        let oC = document.getElementById("c1");
        let oCG = oC.getContext("2d");
        let aBtn = document.querySelectorAll("button");
        class Rain{
            constructor(){
                this.x = Math.round(Math.random()*oC.offsetWidth);
                this.y = Math.round(Math.random()*oC.offsetHeight);
                this.opacity = 1;
                this.colors = [Math.round(Math.random()*255),Math.round(Math.random()*255),Math.round(Math.random()*255)];
                this.color = `rgba(${this.colors[0]},${this.colors[1]},${this.colors[2]},${this.opacity})`;
                this.r = 5;
            }
            draw(){
                oCG.beginPath();
                oCG.save();
                oCG.fillStyle = this.color;
                oCG.arc(this.x,this.y,this.r,0,360*Math.PI/180,false);
                oCG.fill();
                oCG.restore();
                this.opacity -= 1/40;
                this.color = `rgba(${this.colors[0]},${this.colors[1]},${this.colors[2]},${this.opacity})`;
                // console.log(this.color);
                this.r += 45/40;
            }
        }
        let arr = [];
        let timer = null;
        aBtn[0].onclick = function (){
            timer = setInterval(function (){
                let obj1 = new Rain();
                arr.push(obj1);
                oCG.clearRect(0,0,oC.offsetWidth,oC.offsetHeight);
                for(let i=0;i<arr.length;i++){
                    arr[i].draw();
                }
                arr = arr.filter((item,index)=>{
                    return item.opacity>0;
                })
            },30)
        }
        aBtn[1].onclick = function (){
            oCG.clearRect(0,0,oC.offsetWidth,oC.offsetHeight);
            arr = [];
            clearInterval(timer);
        }
    </script>
</body>
</html>
举报

相关推荐

0 条评论