1. 程式人生 > 其它 >html寫流星雨(完整程式碼)

html寫流星雨(完整程式碼)

人生不可能總是順心如意,但持續朝著陽光走,影子就會躲在後面,刺眼,卻是對的方向

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>流星雨</title>
<meta name="keywords" content="關鍵詞,關鍵字">
<meta name="description" content="描述資訊">
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>

<body>

<!--
<canvas>畫布 畫板 畫畫的本子
-->
<canvas width=400 height=400 style="background:#000000;" id="canvas"></canvas>

<!--
javascript
畫筆
-->
<script>

//獲取畫板
//doccument 當前文件
//getElement 獲取一個標籤
//ById 通過Id名稱的方式
//var 宣告一片空間
//var canvas 宣告一片空間的名字叫做canvas
var canvas = document.getElementById("canvas");
//獲取畫板許可權 上下文
var ctx = canvas.getContext("2d");
//讓畫板的大小等於螢幕的大小
/*
思路:
1.獲取螢幕物件
2.獲取螢幕的尺寸
3.螢幕的尺寸賦值給畫板
*/
//獲取螢幕物件
var s = window.screen;
//獲取螢幕的寬度和高度
var w = s.width;
var h = s.height;
//設定畫板的大小
canvas.width = w;
canvas.height = h;

//設定文字大小
var fontSize = 14;
//計算一行有多少個文字 取整數 向下取整
var clos = Math.floor(w/fontSize);
//思考每一個字的座標
//建立陣列把clos 個 0 (y座標儲存起來)
var drops = [];
var str = "qwertyuiopasdfghjklzxcvbnm";
//往數組裡面新增 clos 個 0
for(var i = 0;i<clos;i++) {
drops.push(0);
}

//繪製文字
function drawString() {
//給矩形設定填充色
ctx.fillStyle="rgba(0,0,0,0.05)"
//繪製一個矩形
ctx.fillRect(0,0,w,h);

//新增文字樣式
ctx.font = "600 "+fontSize+"px 微軟雅黑";
//設定文字顏色
ctx.fillStyle = "#00ff00";

for(var i = 0;i<clos;i++) {
//x座標
var x = i*fontSize;
//y座標
var y = drops[i]*fontSize;
//設定繪製文字
ctx.fillText(str[Math.floor(Math.random()*str.length)],x,y);
if(y>h&&Math.random()>0.99){
drops[i] = 0;
}
drops[i]++;
}

}
//定義一個定時器,每隔30毫秒執行一次
setInterval(drawString,30);
</script>
</body>
</html>
執行效果截圖: