DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
純文字打造頁面飄落雨絲的粒子動畫
編輯:CSS詳解     

這個特效有趣的地方在於——它不用任何圖片,而是用大量被絕對定位的小小逗號「,」當作雨滴,讓它們從畫面上方不斷生成、沿著固定角度飄落,形成一幅天女散花般的飛絮或下雨景象。因為每個「雨滴」只是一個文字節點,所以完全不依賴圖檔,非常輕量。

原理解析

程式先以 no 決定雨滴數量,為每顆雨滴建立一組座標與速度陣列(x、y、r、cx、cy)。initRain() 隨機設定初始位置,updateRain() 依半徑 r 與角度(用 sin、cos 運算)推進座標,模擬拋物線式的飄落;一旦超出畫面邊界就由 makeRain() 重新回到頂端再生。最後 setTimeout 每隔 speed 毫秒更新一次位置,雨滴便源源不絕地飄落。

<html>
<head>
<title>純文字飛絮下雨效果</title>
</head>
<body>
<script language="JavaScript">
<!--
var no = 50;        // 雨滴數量
var speed = 1;      // 更新間隔
var ns4up = (document.layers) ? 1 : 0;
var ie4up = (document.all) ? 1 : 0;
var s, x, y, sn, cs, a, r, cx, cy, i;
var doc_width = 800, doc_height = 600;
if (ns4up) { doc_width = self.innerWidth; doc_height = self.innerHeight; }
else if (ie4up) { doc_width = document.body.clientWidth; doc_height = document.body.clientHeight; }

x = new Array(); y = new Array(); r = new Array();
cx = new Array(); cy = new Array();
s = 8;

for (i = 0; i < no; ++i) {
  initRain();
  if (ns4up) {
    document.write('<layer name="dot'+i+'" left="1" top="1" visibility="show">'
      + '<font color="red">,</font></layer>');
  } else if (ie4up) {
    document.write('<div id="dot'+i+'" style="POSITION:absolute; Z-INDEX:'+i
      +'; VISIBILITY:visible; TOP:15px; LEFT:15px;">'
      + '<font color="red">,</font></div>');
  }
}

function initRain() {
  a = 6;
  r[i] = 1;
  sn = Math.sin(a);
  cs = Math.cos(a);
  cx[i] = Math.random() * doc_width + 1;
  cy[i] = Math.random() * doc_height + 1;
  x[i] = r[i] * sn + cx[i];
  y[i] = cy[i];
}
function makeRain() {
  r[i] = 1;
  cx[i] = Math.random() * doc_width + 1;
  cy[i] = 1;
  x[i] = r[i] * sn + cx[i];
  y[i] = r[i] * cs + cy[i];
}
function updateRain() {
  r[i] += s;
  x[i] = r[i] * sn + cx[i];
  y[i] = r[i] * cs + cy[i];
}
function raindropIE() {
  for (i = 0; i < no; ++i) {
    updateRain();
    if ((x[i] <= 1) || (x[i] >= (doc_width - 20)) || (y[i] >= (doc_height - 20))) {
      makeRain();
      doc_width = document.body.clientWidth;
      doc_height = document.body.clientHeight;
    }
    document.all["dot"+i].style.top = y[i];
    document.all["dot"+i].style.left = x[i];
  }
  setTimeout("raindropIE()", speed);
}
if (ie4up) raindropIE();
//-->
</script>
</body>
</html>

把雨滴字元從逗號改成「*」「·」或自訂的 Unicode 符號,再調整 color 與 no(數量),就能變化出雪花、花瓣、流星等各種氛圍;加大 speed 可讓飄落更慢更柔。這種以文字節點充當粒子的思路,在今日也能延伸為用 <canvas> 繪製更精緻的粒子系統。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved