浅尝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)