用canvas绘制自由下落的代码雨背景

这篇博客展示了如何使用HTML5的Canvas API创建一个炫酷的动态背景,以文字雨的形式呈现。通过循环绘制不同颜色和位置的文字,实现了一个适用于网页背景的视觉效果。代码中详细解释了画布设置、文字生成和颜色选择的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

浅尝canvas 绘制一个适用于做背景的炫酷方案 

html 代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>canvas特效雨</title>
    <link rel="stylesheet" href="./demo.css">
</head>

<body>
    <canvas id="bg"></canvas>

    <script src="./demo.js"></script>

</body>

</html>

js部分

//获取canvas元素
const  cvs=document.getElementById("bg")
const width=window.innerWidth,
height=window.innerHeight
//设置canvas 尺寸为窗口尺寸
cvs.width=width
cvs.height=height

//获取绘制上下文
const ctx=cvs.getContext('2d')
 
//列宽
const  columnWidth=20;

 const columnCount=Math.floor(window.innerWidth/columnWidth)//列数
 console.log("11",columnCount)
 //记录每一列写到了第几个文字
 const columnNextIndexes=new Array(columnCount);
 columnNextIndexes.fill(1);

 //绘画的函数
 function draw(){

    ctx.fillStyle='rgba(30,30,30,0.3)'//设置覆盖背景
 
    ctx.fillRect(0,0,width,height)//进行页面覆盖
    const fz=25;
    ctx.fillStyle=getRandomColor();
    ctx.font=`${fz}px "Roboto Mono"`//设置字体大小和主题
    //循环列
    for(let i=0;i<columnCount;i++){
        let x=i*columnWidth
        let y=fz*columnNextIndexes[i]
        ctx.fillText(getRandomChar(),x,y)
        if(y>height && Math.random()>0.99){
            columnNextIndexes[i]=0
        }else{

            columnNextIndexes[i]++
        }
    }
    // ctx.fillText('a',100,100)
 }

 //随机颜色
 function getRandomColor(){
    const fontColors=[

        '#33B5E5',
        '#0099CC',
        '#AA66CC',
        '#4ec9b0',
        '#da70b2',
        '#007acc',
        '#f2e0df'

    ]
    return fontColors[Math.floor(Math.random()*fontColors.length) ]

    
 }
 //获取随机的文字
 function getRandomChar(){
    const str ='console.log("hellow world")';
    return str[Math.floor(Math.random()*str.length)];
 }
 draw()
 setInterval(draw,300)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值