DIV CSS 佈局教程網

用 JavaScript 打造宇宙星空飛行的背景動畫
編輯:關於JavaScript     

很多網站的首屏都喜歡用星空飛行的效果營造科技感。原理其實不複雜:在畫面上鋪滿大量小方塊當作星點,讓它們從畫面中心向外移動,並隨著距離變遠而不斷放大,營造出穿越星海的錯覺。本文分享一個以純 JavaScript 實作的完整範例,靠 setTimeout 驅動動畫,並額外處理了視窗縮放時的重新定位。

實作思路

整個效果可以拆成三件事:

1. 用迴圈動態產生指定數量的 div 節點作為星星;
2. 每顆星星記錄自己的位移速度與方向(用隨機函式決定),中心點即為發源位置;
3. 定時呼叫移動函式,判斷是否超出視窗邊界,超出就重置回中心重新出發。

完整程式碼

<!DOCTYPE html>
<html>
<head>
<TITLE>宇宙星空背景效果,Js 特效</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.star {
    position: absolute;
    visibility: visible;
    top: -50px;
    width: 50px;
    height: 50px;
    font-size: 1px;
    background-color: white;
}
.60pt { font-size: 60pt; color: #ff66cc; }
</style>
<SCRIPT LANGUAGE="JavaScript">
<!--
var starnum = 75; // 星星的數量
var isNS = (document.layers);
var _all = (isNS) ? '' : 'all.';
var _style = (isNS) ? '' : '.style';
var xoffset, yoffset, w_x, w_y, tmpx, tmpy, scrlx, scrly;

// 設定星星的起始位置與飛行方向
function getstartpos(obj) {
    obj.deltay = Math.floor(Math.random() * 12);
    obj.deltax = Math.floor(Math.random() * 12);
    obj.xdir = (Math.floor(Math.random() * 2) == 1) ? '+' : '-';
    obj.ydir = (Math.floor(Math.random() * 2) == 1) ? '+' : '-';
    obj.counter = 1;
    if (isNS) {
        obj.clip.width = 1;
        obj.clip.height = 1;
        obj.moveTo(xoffset + pageXOffset, yoffset + pageYOffset);
    } else {
        obj.width = 1;
        obj.height = 1;
        obj.pixelTop = yoffset + document.body.scrollTop;
        obj.pixelLeft = xoffset + document.body.scrollLeft;
    }
}

// 移動星星,並隨距離放大
function movestar(starN) {
    tmpx = starN.deltax * starN.counter + starN.counter;
    tmpy = starN.deltay * starN.counter + starN.counter;
    if (isNS) {
        starN.clip.width = starN.counter / 3;
        starN.clip.height = starN.counter / 3;
        scrlx = pageXOffset;
        scrly = pageYOffset;
        if ((starN.left + tmpx >= w_x + scrlx) || (starN.top + tmpy >= w_y + scrly) ||
            (starN.left - tmpx <= scrlx) || (starN.top - tmpy <= scrly)) {
            getstartpos(starN);
        } else {
            eval('starN.moveBy(' + starN.xdir + tmpx + ', ' + starN.ydir + tmpy + ')');
        }
    } else {
        starN.width = starN.counter / 3;
        starN.height = starN.counter / 3;
        scrlx = document.body.scrollLeft;
        scrly = document.body.scrollTop;
        if ((starN.pixelLeft + tmpx >= w_x + scrlx) || (starN.pixelTop + tmpy >= w_y + scrly) ||
            (starN.pixelLeft - tmpx <= scrlx) || (starN.pixelTop - tmpy <= scrly)) {
            getstartpos(starN);
        } else {
            eval('starN.pixelTop' + starN.ydir + '=tmpy');
            eval('starN.pixelLeft' + starN.xdir + '=tmpx');
        }
    }
    starN.counter++;
}

// 讓所有星星動起來
function animate() {
    for (i = 1; i <= starnum; i++) {
        movestar(eval('star' + i));
    }
    setTimeout('animate()', 100);
}

// 計算視窗中心作為發源點,並初始化所有星星
function findwindowparams() {
    w_x = (isNS) ? window.innerWidth : document.body.clientWidth;
    w_y = (isNS) ? window.innerHeight : document.body.clientHeight;
    xoffset = w_x / 2;
    yoffset = w_y / 2;
    for (i = 1; i <= starnum; i++) {
        getstartpos(eval('star' + i));
    }
}
function resizeNS() {
    setTimeout('document.location.reload()', 400);
}
(isNS) ? window.onresize = resizeNS : window.onresize = findwindowparams;
window.onload = new Function("findwindowparams(); animate();");
//-->
</script>
</HEAD>
<BODY bgcolor="#999999">
<SCRIPT LANGUAGE="JavaScript">
<!--
for (i = 1; i <= starnum; i++) { // 動態產生星星的層
    document.writeln('<div id="star' + i + '" class="star"></div>');
    eval('var star' + i + ' = document.' + _all + 'star' + i + _style);
}
//-->
</script>
<p><center>
<font class="60pt"><br>飛翔在<br>宇宙的星空中<br></font>
</center>
</body>
</html>

執行結果

幾點提醒

這個範例寫於不支援 Canvas 的年代,因此用 DOM 節點拼貼星點,數量一多就會明顯吃效能。若要在正式專案中使用,建議改用 <canvas> 搭配 requestAnimationFrame 重寫,並把 eval 換成陣列存放節點參照,同時將 setTimeout 的 100 毫秒間隔調整為依實際幀率換算。此外,為尊重有動態敏感困擾的使用者,最好加上 prefers-reduced-motion 的判斷,讓系統偏好設定的使用者看不到這段動畫。

希望本文所述的實作思路對大家的 JavaScript 設計有所幫助。

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