頁面點擊「GO」按鈕,預設詞庫中的單詞在容器內按行排列,隨後像下落的文字雨一樣以隨機速度向下移動,超出容器底部停止。
function Falling() {
this.dict = ["abcd","2222","sign","next","container","content","last","break",
"less","than","that","absolute","relative","my","index","html",
"java","c#","web","javascript","php","include","shit","bull",
"big","smart","call","apply","callee","caller","function"];
this.canvas = $("#canvas");
this.step = 15; // 佈局行高
this.freq = 10; // 動畫幂間隔 ms
this.height = 500; // 容器高度
this.width = 500; // 容器寬度
this.si = null; // 定時器 ID
}
Falling.prototype.init = function() {
var self = this;
self.canvas.html(''); // 清空
var dom = [];
var l = 0, t = 0; // 當前行列偏移
var tempDom = $("").appendTo("body");
for (var i = 0; i < self.dict.length; i++) {
dom[i] = $("" + self.dict[i] + "").appendTo(tempDom);
var w = dom[i].width(), h = dom[i].height();
// 簡易換行佈局
if (t < self.height) {
if (l < self.width) {
if (w + l <= self.width) { // 當前行放得下
dom[i].css({top: t, left: l});
self.canvas.append(dom[i]);
l += w;
} else { // 換行
if (h + t <= self.height) {
t += h; l = 0;
dom[i].css({top: t, left: l});
self.canvas.append(dom[i]);
l = w;
} else break; // 超出容器高度
}
} else { // 換行
if (h + t <= self.height) {
t += h; l = 0;
dom[i].css({top: t, left: l});
self.canvas.append(dom[i]);
} else break;
}
} else break;
}
self.fallingAction(dom); // 啟動動畫
};
使用隱藏容器 tempDom 先渲染測量寬高,再按行佈局到可視容器。
Falling.prototype.fallingAction = function(dom) {
var self = this;
var freqs = [10, 15, 20]; // 隨機下落速度
var disS = []; // 當前下落距離
var disPerFreqS = []; // 每幂步長
var targetDis = 500; // 目標距離(容器高度)
var domCssTopS = []; // 初始 top
var successDom = []; // 完成標誌
var successCount = 0;
var total = dom.length;
for (var i = 0; i < total; i++) {
domCssTopS[i] = dom[i].position().top;
disS[i] = 0;
disPerFreqS[i] = freqs[Math.floor(Math.random() * freqs.length)];
}
self.si = setInterval(function() {
if (successCount >= total) { clearInterval(self.si); return; }
for (var i = 0; i < total; i++) {
if (successDom[i] === "ok") continue;
disS[i] += disPerFreqS[i];
if (disS[i] >= targetDis) {
dom[i].css("top", targetDis + domCssTopS[i]);
successDom[i] = "ok"; successCount++;
} else {
dom[i].css("top", disS[i] + domCssTopS[i]);
}
}
}, self.freq);
};
span,數百詞導致重排重繪極其昂貴。position()、css()、append() 封裝開銷大。// Canvas 版本核心邏輯
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const words = [...]; // 詞庫
const particles = words.map(w => ({
x: Math.random() * canvas.width,
y: -Math.random() * canvas.height,
speed: 1 + Math.random() * 3,
text: w,
font: '16px Microsoft YaHei'
}));
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = '16px Microsoft YaHei';
ctx.fillStyle = '#fff';
particles.forEach(p => {
ctx.fillText(p.text, p.x, p.y);
p.y += p.speed;
if (p.y > canvas.height) p.y = -20; // 循環
});
requestAnimationFrame(animate);
}
animate();
優勢:單 Canvas 繪製、GPU 加速、無 DOM 開銷、幂率穩定 60fps、易擴展粒子效果(旋轉、縮放、淡入淡出)。
prefers-reduced-motion 媒體查詢關閉動畫。