作者看到 Flash 做這類光效相當容易,於是嘗試用純 DOM 拼湊出來。做法是把每一個「像素」都畫成一個 <p> 元素,靠大量小方塊排成光帶,再用三角函數讓整條光帶上下起伏。
point 方法負責產生單一像素:一個寬 1px、高 n px 的绝对定位方塊。wave 方法則用兩層迴圈排出上下對稱的三角形截面,形成尖銳的光帶輪廓;color 隨機挑一個偏亮的色碼,讓每次生成都有微妙差異。
<script>
var lightWave = function (T, left, thick, sharp, speed, vibration, amplitude, opacity) {
this.cont = T; // 炫光容器
this.left = left; // 炫光向右偏移量
this.thick = thick; // 粗細
this.sharp = sharp; // 尖銳度
this.speed = speed; // 波動速度
this.vibration = vibration; // 單位時間內的振動頻率
this.amplitude = amplitude; // 振幅
this.opacity = opacity; // 透明度
this.cont.style.position = 'relative';
this.move();
};
lightWave.prototype = {
point: function (n, l, t, c, color) {
var p = document.createElement('p');
p.innerHTML = ' ';
p.style.top = t + 'px';
p.style.left = l + 'px';
p.style.width = 1 + 'px';
p.style.height = n + 'px';
p.style.filter = 'alpha(opacity=' + this.opacity + ')';
p.style.lineHeight = 0;
p.style.position = 'absolute';
p.style.background = color;
c.appendChild(p);
return this;
},
color: function () {
var c = ['0','3','6','9','c','f'];
var t = [c[Math.floor(Math.random() * 100) % 6], '0', 'f'];
t.sort(function () { return Math.random() > 0.5 ? -1 : 1; });
return '#' + t.join('');
},
wave: function () {
var l = this.left, color = this.color();
var c = document.createElement('div');
c.style.top = this.amplitude + 20 + 'px';
c.style.position = 'absolute';
c.style.opacity = this.opacity / 100;
for (var i = 1; i < this.thick; i++) {
for (var j = 0; j < this.thick * this.sharp - i * i; j++, l++) {
this.point(i, l, -9999, c, color);
}
}
for (var i = this.thick; i > 0; i--) {
for (var j = this.thick * this.sharp - i * i; j > 0; j--, l++) {
this.point(i, l, -9999, c, color);
}
}
this.cont.appendChild(c);
return c;
},
move: function () {
var wl = this.amplitude;
var vibration = this.vibration;
var w = this.wave().getElementsByTagName('p');
for (var i = 0; i < w.length; i++) { w[i].i = i; }
var m = function () {
for (var i = 0, len = w.length; i < len; i++) {
var top;
if (w[i].ori == true) {
w[i].i -= vibration;
top = w[i].i % 180 == 90 ? 0 : wl * Math.cos(w[i].i * Math.PI / 180);
w[i].style.top = top + 'px';
if (parseFloat(w[i].style.top) <= -wl) w[i].ori = false;
} else {
w[i].i += vibration;
top = w[i].i % 180 == 90 ? 0 : wl * Math.cos(w[i].i * Math.PI / 180);
w[i].style.top = top + 'px';
if (parseFloat(w[i].style.top) >= wl) w[i].ori = true;
}
}
};
setInterval(m, this.speed);
}
};
window.onload = function () {
var targetDom = document.body;
new lightWave(targetDom, 0, 3, 36, 120, 6, 20, 40);
new lightWave(targetDom, 50, 2, 70, 120, 10, 30, 30);
};
</script>
<body style="background:#000;margin-top:100px"></body>
建構子共八個參數:容器、起始向右偏移、粗細、尖銳程度、波動速度、振動頻率、振幅、透明度。調整這些數字就能產生不同性格的光帶——例如把 sharp 調大會更尖銳,amplitude 調大起伏更明顯。
原文提到在 IE 下透明度 filter 不起作用,原因是改變父容器的定位會影響子節點 filter 的繼承。這類問題在現代已不復存在。
更重要的是效能:用成千上萬個 DOM 元素當像素,每帧还要逐一改 style,在今天的低階手机上依然吃力。若要重現同樣的效果,正確工具是 <canvas> 搭配 requestAnimationFrame,或直接用 WebGL/CSS gradient 與 filter: blur()。DOM 大量節點的動畫,永遠不該是第一選擇。