原生js,通过canvas实现数字雨

效果图:

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        canvas{
            border: 1px solid #000;
        }
    </style>
</head>
<body>
<canvas width="900" height="600"></canvas>
<script>
    var mcanvas=document.getElementsByTagName("canvas")[0];
    var ctx=mcanvas.getContext("2d");
    var mw=mcanvas.width;
    var mh=mcanvas.height;
    var str="0123456789abcdefghijklmnopqrstuvwxyz";
    var fontSize=15;
    var wCount=mw/fontSize;
    var hCount=mh/fontSize;
//    var index=0;
    var content=[];
    for(var a=0;a<wCount;a++){
        content[a]=0;
    }
    var timer=setInterval(function(){
        ctx.fillStyle="rgba(0,0,0,0.1)";
        ctx.fillRect(0,0,900,600);
        for(var i=0;i<wCount;i++){
            ctx.font="fontSize '微软雅黑'";
            ctx.textBaseline="top";
            ctx.textAlign="center";
            ctx.fillStyle="#ccc";
            var suiji=Math.random()*str.length;
            ctx.fillText(str[Math.floor(suiji)],fontSize*i,content[i]*fontSize);
            content[i]++;
            if(content[i]*fontSize>mh || Math.random()<0.1){
                content[i]=0;
            }
        }c
    },100)
</script>
</body>
</html>

支持原创

猜你喜欢

转载自blog.csdn.net/ramosTears123/article/details/88779111