文字雨
<head>
<meta charset="UTF-8">
<title>文字雨</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html {
overflow: hidden;
}
</style>
</head>
<body>
<input type="button" onclick="operateAnimation(this)" name="" id="" value="暂停" />
<br />
<canvas id="canvas" style="background-color: yellowgreen;"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//获取浏览器屏幕的宽度和高度,处理兼容
var W = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var H = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
//设置canvas的宽度和高度
canvas.width = W;
canvas.height = H;
//每个文字的字体大小
var fontSize = 16;
//计算列
var colunms = Math.floor(W / fontSize);
//Math.floor() === 向下取整
//记录每列文字的y轴坐标
var drops = [];
//给每一个文字初始化一个起始点的位置
for(var i = 0; i < colunms; i++) {
drops.push(0);
}
// console.log(drops)
//运动的文字
var str = "显示的运动字体";
function draw() {
context.fillStyle = "rgba(0,0,0,0.05)";
context.fillRect(0, 0, W, H);
context.font = "700 " + fontSize + "px 微软雅黑";
context.fillStyle = "red"; //可以rgb,hsl, 标准色,十六进制颜色
循环字体---写入画布中
for(var i = 0; i < colunms; i++) {
//随机汉字打印
var index = Math.floor(Math.random() * str.length);
//Math.random()方法可返回介于 0 ~ 1 之间的一个随机数
//index为随机整数
var x = i * fontSize; //x坐标
var y = drops[i] * fontSize; //y坐标
context.fillText(index, x, y);
if(y >= canvas.height && Math.random() > 0.99) {
drops[i] = 0;
}
//增加的Y坐标
drops[i]++;
}
};
draw();
var intervalId = setInterval(draw, 30);
// 测试效果开始/暂停
function operateAnimation(objBtn) {
var operate = document.getElementById("operate");
if(objBtn.value == "开始") {
objBtn.value = "暂停";
intervalId = setInterval(draw, 30);
} else {
objBtn.value = "开始";
clearInterval(intervalId);## 标题
}
return false;
}
</script>
</body>