欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

canvas冒泡demo(二)

程序员文章站 2022-03-15 12:36:18
...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style type="text/css">
    *{
        margin: 0px;
        padding: 0px;
    }
    body{
        background-color: gray;
    }
    canvas{
        position: absolute;
        left: 0px;
        right: 0px;
        top: 0px;
        bottom: 0px;
        margin: auto;
        background-color: white;
    }
</style>

<body>
<canvas width="150px" height="400px"></canvas>
</body>


<script>
    window.onload = function () {
        const oc = document.querySelector('canvas');
        if (oc.getContext){
            const ctx = oc.getContext('2d');

            let arr=[];

            //绘制
            setInterval(function () {
                //清画布
                console.log(arr)
                ctx.clearRect(0,0,oc.width,oc.height);
                //曲线
                for (let i=0;i<arr.length;i++){
                    arr[i].deg+=5;
                    //圆心;step控制曲线运动形式
                    arr[i].x = arr[i].startX + Math.sin(arr[i].deg*Math.PI/180)*arr[i].step*2;
                    arr[i].y = arr[i].startY - (arr[i].deg*Math.PI/180)*arr[i].step/2;
                    if (arr[i].y<50){arr.splice(i,1);}
                }

                for (let i=0;i<arr.length;i++){
                    ctx.save();
                    //随机颜色
                    ctx.fillStyle = "rgba("+ arr[i].red + ","+ arr[i].green + "," + arr[i].blue + "," + arr[i].a + ")";
                    ctx.beginPath();

                    //随机圆
                    ctx.arc(arr[i].x,arr[i].y,arr[i].r,0,2*Math.PI);
                    ctx.fill();
                    ctx.restore();
                }
            },1000/60)

            //往arr中注入随机园信息,间歇调用
            setInterval(function () {
                const r = Math.random()*6+2;
                const x = Math.random()*oc.width;
                const y = oc.height - r;

                const red = Math.round(Math.random()*255);
                const green = Math.round(Math.random()*255);
                const blue = Math.round(Math.random()*255);
                const a = 1;

                //度数
                const deg = 0;

                startX = x;
                startY = y;
                const step = Math.random()*10+2;
                arr.push({
                    x:x,
                    y:y,
                    r:r,
                    red:red,
                    green:green,
                    blue:blue,
                    a:a,
                    deg:deg,
                    startX:startX,
                    startY:startY,
                    step:step,
                })
            },300)

            //ctx.fillStyle="#0000ff";
            //ctx.arc(100,75,10,0,2*Math.PI);
            //ctx.fill();
        }
    }
</script>
</html>

```![在这里插入图片描述](https://img-blog.csdnimg.cn/20190322134345676.png)
相关标签: demo