本篇文章給大家分享HTML5 canvas代碼流瀑布的具體代碼。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)大家有所幫助。
在js部分寫canvas代碼,有詳細(xì)注釋
html部分:
一個(gè)canvas元素:
<canvas id="canvas" ></canvas>
css部分:
<style> *{ padding: 0; margin: 0; } canvas{ background-color: #111; } body{ overflow: hidden; } </style>
js部分
<script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); // 獲取瀏覽器的寬度和高度 var w = window.innerWidth; var h = window.innerHeight; // 設(shè)置canvas的寬高 canvas.width = w; canvas.height = h; // 每個(gè)文字的大小 var fontSize = 16; // 一共可以有多少列文字 var col = Math.floor(w / fontSize); // 記錄每列文字的y軸坐標(biāo) var cpy = []; for(var i = 0;i< col; i++) { cpy[i] = 1; } //定義文字 var str = "Javascriphafhsdhfsfsf{}"; // 繪制 draw(); setInterval(draw,30); function draw(){ context.beginPath(); // 背景填充顏色 context.fillStyle = "rgba(0,0,0,0.05)"; context.fillRect(0,0,w,h); // 設(shè)置字體大小 context.font = fontSize +"px bold 微軟雅黑 "; // 設(shè)置字體顏色 context.fillStyle = "#00cc33"; for(var i = 0; i < col;i++) { var index = Math.floor(Math.random()*str.length); var x = i*fontSize; var y = cpy[i]*fontSize; context.fillText(str.charAt(index),x,y); if(y >= h && Math.random()> 0.99)// 出現(xiàn)時(shí)間延遲的效果 { cpy[i]=0;// 只要Math.random> 0.99 時(shí)才縱坐標(biāo)從0開始寫字 } cpy[i]++;// 數(shù)組值加一,以便下一次寫的字在下面一行 } } </script>
動(dòng)態(tài)效果圖:
更多炫酷特效,推薦訪問(wèn):js特效大全!