如果你的电脑设置了屏保(屏幕保护),长时间不动屏保就会显示出来。尤其是一些绚丽的屏保,拥有流畅的动画。今天我们就用 HTML5 的 Canvas 功能实现一款仿文字雨黑客帝国特效的屏保。
下面我们先看一下运行效果:

上面这张图片不是动画,如果截的是动画,看起来就和流星雨一样。下面说说实现原理。
首先编写一个 Canvas,然后随机产生字母,然后让这些字母掉落。全部实现代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="c"></canvas>
<script>
var c=document.getElementById("c");
var ctx=c.getContext("2d");
c.width=window.innerWidth;
c.height=window.innerHeight;
// ctx.fillRect(0,0,100,100);
// a,b,c,d分别代表x方向偏移,y方向偏移,宽,高
var string1 = "abcdefghijklmnopqrstuvwxyz";
string1.split("");
var fontsize=20;
columns=c.width/fontsize;
var drop = [];
for(var x=0;x<columns;x++){
drop[x]=0;
}
function drap(){
ctx.fillStyle="rgba(0,0,0,0.07)";
ctx.fillRect(0,0,c.width,c.height);
ctx.fillStyle="#0F0";
ctx.font=fontsize+"px arial";
for(var i=0;i<drop.length;i++){
var text1=string1[Math.floor(Math.random()*string1.length)];
ctx.fillText(text1,i*fontsize,drop[i]*fontsize);
drop[i]++;
if(drop[i]*fontsize>c.height&&Math.random()>0.9){//90%的几率掉落
drop[i]=0;
}
}
}
setInterval(drap,20);
</script>
</body>
</html>
非常少的代码,实现非常炫的效果,这就是 HTML5 和 Canvas 的魅力所在。

: » 使用Canvas实现黑客帝国数字雨屏保
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/251229.html