1. 程式人生 > 實用技巧 >【JS】程式碼雨特效

【JS】程式碼雨特效

html程式碼
<canvas id="code_rain_canvas" width="1440" height="900"></canvas>
js 程式碼
window.onload = function() {
         //獲取畫布物件
         var canvas = document.getElementById("code_rain_canvas");
         //獲取畫布的上下文
         var context = canvas.getContext("2d");
         var s = window.screen;
         
var W = canvas.width = s.width; var H = canvas.height; //獲取瀏覽器螢幕的寬度和高度 //var W = window.innerWidth; //var H = window.innerHeight; //設定canvas的寬度和高度 canvas.width = W; canvas.height = H; //每個文字的字型大小 var fontSize = 12; //計算列 var
colunms = Math.floor(W / fontSize); //記錄每列文字的y軸座標 var drops = []; //給每一個文字初始化一個起始點的位置 for (var i = 0; i < colunms; i++) { drops.push(0); } //運動的文字 var str = "WELCOME TO WWW.ITRHX.COM"; //4:fillText(str,x,y);原理就是去更改y的座標位置 //
繪畫的函式 function draw() { context.fillStyle = "rgba(238,238,238,.08)"; //遮蓋層 context.fillRect(0, 0, W, H); //給字型設定樣式 context.font = "600 " + fontSize + "px Georgia"; //給字型新增顏色 context.fillStyle = ["#33B5E5", "#0099CC", "#AA66CC", "#9933CC", "#99CC00", "#669900", "#FFBB33", "#FF8800", "#FF4444", "#CC0000"][parseInt(Math.random() * 10)]; //randColor();可以rgb,hsl, 標準色,十六進位制顏色 //寫入畫布中 for (var i = 0; i < colunms; i++) { var index = Math.floor(Math.random() * str.length); var x = i * fontSize; var y = drops[i] * fontSize; context.fillText(str[index], x, y); //如果要改變時間,肯定就是改變每次他的起點 if (y >= canvas.height && Math.random() > 0.99) { drops[i] = 0; } drops[i]++; } }; function randColor() { //隨機顏色 var r = Math.floor(Math.random() * 256); var g = Math.floor(Math.random() * 256); var b = Math.floor(Math.random() * 256); return "rgb(" + r + "," + g + "," + b + ")"; } draw(); setInterval(draw, 35); };
展示效果: