414 lines
20 KiB
JavaScript
414 lines
20 KiB
JavaScript
(function(){
|
|
// 初始化函数 用于启动雪花效果
|
|
function init(){
|
|
const canvas = document.getElementById('effectiveAppsSnow');
|
|
// 条件判断 如果未找到画布元素则不执行
|
|
if (!canvas) return;
|
|
const prefersReducedMotion = (typeof window.matchMedia === 'function') && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
if (prefersReducedMotion) { canvas.style.display = 'none'; return; }
|
|
const context = canvas.getContext('2d');
|
|
let viewportWidth = window.innerWidth;
|
|
let viewportHeight = window.innerHeight;
|
|
const devicePixelRatio = window.devicePixelRatio || 1;
|
|
|
|
// 读取首页显示时长设置 单位为秒 0 表示无限
|
|
const displayDurationSeconds = (window.YooneSnowSettings && typeof window.YooneSnowSettings.displayDurationSeconds !== 'undefined')
|
|
? Math.max(0, parseInt(window.YooneSnowSettings.displayDurationSeconds, 10) || 0)
|
|
: 0;
|
|
// 记录启动时间 用于计算已运行时间
|
|
const startTimestamp = performance.now();
|
|
// 标记是否已达到显示时长 到达后不再生成新粒子并不再重生
|
|
let hasReachedDuration = false;
|
|
|
|
const selectedShapes = (window.YooneSnowSettings && Array.isArray(window.YooneSnowSettings.selectedShapes) && window.YooneSnowSettings.selectedShapes.length > 0)
|
|
? window.YooneSnowSettings.selectedShapes
|
|
: ['dot','flake'];
|
|
const mediaItems = (window.YooneSnowSettings && Array.isArray(window.YooneSnowSettings.mediaItems))
|
|
? window.YooneSnowSettings.mediaItems
|
|
: [];
|
|
const emojiItems = (window.YooneSnowSettings && Array.isArray(window.YooneSnowSettings.emojiItems))
|
|
? window.YooneSnowSettings.emojiItems
|
|
: [];
|
|
const textItems = (window.YooneSnowSettings && Array.isArray(window.YooneSnowSettings.textItems))
|
|
? window.YooneSnowSettings.textItems
|
|
: [];
|
|
const defaultShapeWeights = { dot: 1, flake: 4, yuanbao: 1, coin: 1, santa_hat: 1, candy_cane: 1, christmas_sock: 1, christmas_tree: 1, reindeer: 1, christmas_berry: 1 };
|
|
const shapeWeightsRaw = (window.YooneSnowSettings && window.YooneSnowSettings.shapeWeights && typeof window.YooneSnowSettings.shapeWeights === 'object')
|
|
? window.YooneSnowSettings.shapeWeights
|
|
: {};
|
|
const mediaWeightsRaw = (window.YooneSnowSettings && window.YooneSnowSettings.mediaWeights && typeof window.YooneSnowSettings.mediaWeights === 'object')
|
|
? window.YooneSnowSettings.mediaWeights
|
|
: {};
|
|
const emojiWeightsRaw = (window.YooneSnowSettings && window.YooneSnowSettings.emojiWeights && typeof window.YooneSnowSettings.emojiWeights === 'object')
|
|
? window.YooneSnowSettings.emojiWeights
|
|
: {};
|
|
const textWeightsRaw = (window.YooneSnowSettings && window.YooneSnowSettings.textWeights && typeof window.YooneSnowSettings.textWeights === 'object')
|
|
? window.YooneSnowSettings.textWeights
|
|
: {};
|
|
const shapeWeights = {};
|
|
for (let key in defaultShapeWeights){
|
|
const val = typeof shapeWeightsRaw[key] !== 'undefined' ? parseInt(shapeWeightsRaw[key], 10) : defaultShapeWeights[key];
|
|
shapeWeights[key] = isNaN(val) ? defaultShapeWeights[key] : Math.max(0, val);
|
|
}
|
|
// 移除单独的尺寸与偏移缩放 直接使用最小半径与最小摆动作为缩放系数
|
|
const radiusMinRaw = (window.YooneSnowSettings && typeof window.YooneSnowSettings.radiusMin !== 'undefined')
|
|
? parseFloat(window.YooneSnowSettings.radiusMin)
|
|
: 1.0;
|
|
const radiusMaxRaw = (window.YooneSnowSettings && typeof window.YooneSnowSettings.radiusMax !== 'undefined')
|
|
? parseFloat(window.YooneSnowSettings.radiusMax)
|
|
: 3.0;
|
|
const driftMinRaw = (window.YooneSnowSettings && typeof window.YooneSnowSettings.driftMin !== 'undefined')
|
|
? parseFloat(window.YooneSnowSettings.driftMin)
|
|
: 0.4;
|
|
const driftMaxRaw = (window.YooneSnowSettings && typeof window.YooneSnowSettings.driftMax !== 'undefined')
|
|
? parseFloat(window.YooneSnowSettings.driftMax)
|
|
: 1.0;
|
|
const swingMinRaw = (window.YooneSnowSettings && typeof window.YooneSnowSettings.swingMin !== 'undefined')
|
|
? parseFloat(window.YooneSnowSettings.swingMin)
|
|
: 0.2;
|
|
const swingMaxRaw = (window.YooneSnowSettings && typeof window.YooneSnowSettings.swingMax !== 'undefined')
|
|
? parseFloat(window.YooneSnowSettings.swingMax)
|
|
: 1.0;
|
|
const radiusMin = isNaN(radiusMinRaw) ? 1 : Math.max(0, radiusMinRaw);
|
|
const radiusMax = isNaN(radiusMaxRaw) ? 3 : Math.max(radiusMin, radiusMaxRaw);
|
|
const driftMin = isNaN(driftMinRaw) ? 0.4 : Math.max(0, driftMinRaw);
|
|
const driftMax = isNaN(driftMaxRaw) ? 1.0 : Math.max(driftMin, driftMaxRaw);
|
|
const swingMin = isNaN(swingMinRaw) ? 0.2 : Math.max(0, swingMinRaw);
|
|
const swingMax = isNaN(swingMaxRaw) ? 1.0 : Math.max(swingMin, swingMaxRaw);
|
|
|
|
// 函数 调整画布尺寸并设置像素比 保证清晰显示
|
|
function resizeCanvas(){
|
|
viewportWidth = window.innerWidth;
|
|
viewportHeight = window.innerHeight;
|
|
const displayWidth = viewportWidth;
|
|
const displayHeight = viewportHeight;
|
|
canvas.style.width = displayWidth + 'px';
|
|
canvas.style.height = displayHeight + 'px';
|
|
canvas.width = Math.floor(displayWidth * devicePixelRatio);
|
|
canvas.height = Math.floor(displayHeight * devicePixelRatio);
|
|
context.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);
|
|
}
|
|
|
|
resizeCanvas();
|
|
|
|
// 读取在屏最大数量设置 0 表示自动根据视口面积
|
|
const maxCountRaw = (window.YooneSnowSettings && typeof window.YooneSnowSettings.maxCount !== 'undefined')
|
|
? parseInt(window.YooneSnowSettings.maxCount, 10)
|
|
: 0;
|
|
const isSmallScreen = Math.min(viewportWidth, viewportHeight) <= 768;
|
|
const computedAutoCount = Math.floor(Math.min(isSmallScreen ? 240 : 400, Math.max(isSmallScreen ? 80 : 120, (viewportWidth * viewportHeight) / (isSmallScreen ? 24000 : 12000))));
|
|
const snowflakesTargetCount = Math.max(1, (isNaN(maxCountRaw) || maxCountRaw <= 0) ? computedAutoCount : maxCountRaw);
|
|
const snowflakes = [];
|
|
// 定义连续生成控制参数 使用时间积累的方式平滑新增
|
|
let spawnAccumulator = 0;
|
|
let lastUpdateTimestamp = performance.now();
|
|
// 定义黄金比例相位用于水平位置分布避免聚集
|
|
let spawnPhase = Math.random();
|
|
const goldenRatio = 0.61803398875;
|
|
// 函数 按权重选择形状或媒体图像
|
|
function selectWeightedItem(){
|
|
const items = [];
|
|
for (let sIndex = 0; sIndex < selectedShapes.length; sIndex++){
|
|
const shapeKey = selectedShapes[sIndex];
|
|
const weightVal = typeof shapeWeights[shapeKey] !== 'undefined' ? shapeWeights[shapeKey] : 1;
|
|
if (weightVal > 0){
|
|
// 条件判断 普通形状直接加入 不含 emoji
|
|
items.push({ kind: 'shape', key: shapeKey, weight: weightVal });
|
|
}
|
|
}
|
|
// Emoji 候選獨立加入 不依賴 Shapes 是否包含 emoji
|
|
if (emojiItems.length > 0){
|
|
for (let eIndex = 0; eIndex < emojiItems.length; eIndex++){
|
|
const ch = String(emojiItems[eIndex] || '').trim();
|
|
if (ch === ''){ continue; }
|
|
const ewRaw = typeof emojiWeightsRaw[ch] !== 'undefined' ? parseInt(emojiWeightsRaw[ch], 10) : 1;
|
|
const ew = isNaN(ewRaw) ? 1 : Math.max(0, ewRaw);
|
|
if (ew > 0){ items.push({ kind: 'emoji', text: ch, weight: ew }); }
|
|
}
|
|
}
|
|
if (textItems.length > 0){
|
|
for (let tIndex = 0; tIndex < textItems.length; tIndex++){
|
|
const tx = String(textItems[tIndex] || '').trim();
|
|
if (tx === ''){ continue; }
|
|
const twRaw = typeof textWeightsRaw[tx] !== 'undefined' ? parseInt(textWeightsRaw[tx], 10) : 1;
|
|
const tw = isNaN(twRaw) ? 1 : Math.max(0, twRaw);
|
|
if (tw > 0){ items.push({ kind: 'text', text: tx, weight: tw }); }
|
|
}
|
|
}
|
|
for (let mIndex = 0; mIndex < mediaItems.length; mIndex++){
|
|
const mediaUrl = mediaItems[mIndex];
|
|
const mediaWeight = typeof mediaWeightsRaw[mediaUrl] !== 'undefined' ? parseInt(mediaWeightsRaw[mediaUrl], 10) : 1;
|
|
const finalMediaWeight = isNaN(mediaWeight) ? 1 : Math.max(0, mediaWeight);
|
|
if (finalMediaWeight > 0){
|
|
items.push({ kind: 'media', url: mediaUrl, weight: finalMediaWeight });
|
|
}
|
|
}
|
|
// 条件判断 如果没有可选项则回退为点形状
|
|
if (items.length === 0){
|
|
return { type: 'dot', url: null, text: null };
|
|
}
|
|
let totalWeight = 0;
|
|
for (let i = 0; i < items.length; i++){
|
|
totalWeight += items[i].weight;
|
|
}
|
|
const r = Math.random() * totalWeight;
|
|
let acc = 0;
|
|
for (let i = 0; i < items.length; i++){
|
|
acc += items[i].weight;
|
|
// 条件判断 如果随机值落在当前累计权重内则选择该项
|
|
if (r <= acc){
|
|
if (items[i].kind === 'shape'){
|
|
return { type: items[i].key, url: null, text: null };
|
|
} else {
|
|
if (items[i].kind === 'media'){
|
|
return { type: 'media_image', url: items[i].url, text: null };
|
|
} else {
|
|
if (items[i].kind === 'emoji'){
|
|
return { type: 'emoji_text', url: null, text: items[i].text };
|
|
} else {
|
|
return { type: 'text_label', url: null, text: items[i].text };
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return { type: 'dot', url: null, text: null };
|
|
}
|
|
function createSnowflake(preferredX, preferredY){
|
|
const picked = selectWeightedItem();
|
|
let chosenType = picked.type;
|
|
let chosenImageUrl = picked.url;
|
|
let chosenEmojiText = picked.text;
|
|
return {
|
|
positionX: typeof preferredX === 'number' ? preferredX : Math.random() * viewportWidth,
|
|
positionY: typeof preferredY === 'number' ? preferredY : (-1 - Math.random() * 4),
|
|
// 半径使用随机范围并乘以最小半径作为缩放因子
|
|
radius: (Math.random() * (radiusMax - radiusMin) + radiusMin) * radiusMin,
|
|
driftSpeed: Math.random() * (driftMax - driftMin) + driftMin,
|
|
// 水平摆动使用随机范围并乘以最小摆动作为缩放因子
|
|
swingAmplitude: (Math.random() * (swingMax - swingMin) + swingMin) * swingMin,
|
|
shapeType: chosenType,
|
|
imageUrl: chosenImageUrl,
|
|
emojiText: chosenEmojiText,
|
|
// 标记该粒子是否已经移出视口 用于停止后清理
|
|
outOfView: false
|
|
};
|
|
}
|
|
// 计算平均垂直速度 辅助估算生成速率 保证视觉连续
|
|
function computeAverageVerticalSpeed(){
|
|
let countInView = 0;
|
|
let speedSum = 0;
|
|
for (let idx = 0; idx < snowflakes.length; idx++){
|
|
const flake = snowflakes[idx];
|
|
if (flake.outOfView){ continue; }
|
|
const verticalSpeed = flake.driftSpeed * 2 + flake.radius * 0.25;
|
|
speedSum += verticalSpeed;
|
|
countInView++;
|
|
}
|
|
if (countInView > 0){
|
|
return speedSum / countInView;
|
|
}
|
|
const driftAverage = (driftMin + driftMax) * 0.5;
|
|
const radiusAverage = ((radiusMin + radiusMax) * 0.5) * radiusMin;
|
|
return driftAverage * 2 + radiusAverage * 0.25;
|
|
}
|
|
|
|
// 函数 根据视口高度 目标最大数量 与平均速度估算初始化预填充数量
|
|
function estimateInitialPrefillCount(){
|
|
// 計算平均垂直速度 用於估算雪花生命周期
|
|
const averageVerticalSpeed = computeAverageVerticalSpeed();
|
|
const averageLifeSeconds = (viewportHeight + 5) / Math.max(0.001, averageVerticalSpeed);
|
|
// 計算每秒需要補給的雪花數量 以維持目標密度
|
|
const supplyRatePerSecond = snowflakesTargetCount / Math.max(0.001, averageLifeSeconds);
|
|
// 設置預熱時長 避免開場過空或過密 隨速度自適應
|
|
const warmupSeconds = Math.min(2.0, Math.max(0.8, averageLifeSeconds * 0.25));
|
|
// 初始預填充數量 取補給速率乘以預熱時長 並限制在合理範圍
|
|
const rawCount = Math.floor(supplyRatePerSecond * warmupSeconds);
|
|
const boundedCount = Math.min(snowflakesTargetCount, Math.max(10, rawCount));
|
|
return boundedCount;
|
|
}
|
|
|
|
// 函数 封装添加雪花的操作 支持指定水平与垂直位置
|
|
function pushSnowflake(preferredX, preferredY){
|
|
snowflakes.push(createSnowflake(preferredX, preferredY));
|
|
}
|
|
|
|
// 函数 初始化预填充雪花 保持从顶部下落的感觉并避免过量
|
|
function initSnowPrefill(){
|
|
// 条件判断 仅在未达到时长且当前未生成过雪花时执行
|
|
if (hasReachedDuration){ return; }
|
|
if (snowflakes.length > 0){ return; }
|
|
const initialCount = estimateInitialPrefillCount();
|
|
for (let spawnIndex = 0; spawnIndex < initialCount; spawnIndex++){
|
|
// 使用黄金比例相位分布水平位置 减少聚集
|
|
const preferredX = (spawnPhase % 1) * viewportWidth;
|
|
spawnPhase = (spawnPhase + goldenRatio) % 1;
|
|
// 仅在顶部附近生成 保持从顶部下落的视觉感受
|
|
const preferredY = -3 - Math.random() * 6;
|
|
pushSnowflake(preferredX, preferredY);
|
|
}
|
|
}
|
|
|
|
// 調用初始化預填充
|
|
initSnowPrefill();
|
|
|
|
// 函数 更新雪花位置与视口状态
|
|
function updateSnowflakes(){
|
|
for (let j = 0; j < snowflakes.length; j++){
|
|
const flake = snowflakes[j];
|
|
flake.positionY += flake.driftSpeed * 2 + flake.radius * 0.25;
|
|
flake.positionX += Math.sin(flake.positionY * 0.01) * flake.swingAmplitude;
|
|
// 条件判断 如果超出视口底部则标记为已移出
|
|
if (flake.positionY > viewportHeight + 5){
|
|
flake.outOfView = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 使用全局渲染注册表 根据形状类型选择渲染函数
|
|
|
|
// 函数 清空画布并绘制可见雪花
|
|
function drawSnowflakes(){
|
|
context.clearRect(0, 0, viewportWidth, viewportHeight);
|
|
|
|
for (let k = 0; k < snowflakes.length; k++){
|
|
const flake = snowflakes[k];
|
|
// 条件判断 如果该粒子已移出视口则不再绘制
|
|
if (flake.outOfView){ continue; }
|
|
// 条件判断 如果是媒体图片类型则使用通用图像渲染
|
|
if (flake.shapeType === 'media_image' && flake.imageUrl){
|
|
const record = window.YooneSnowGetOrLoadImage ? window.YooneSnowGetOrLoadImage(flake.imageUrl) : { img: null, ready: false };
|
|
if (record && record.ready){
|
|
const targetHeight = flake.radius * 8;
|
|
const targetWidth = targetHeight;
|
|
window.YooneSnowDrawCenteredImage(context, record.img, flake.positionX, flake.positionY, targetWidth, targetHeight);
|
|
}
|
|
continue;
|
|
}
|
|
// 条件判断 如果是 emoji 文本类型則使用文本繪制
|
|
if (flake.shapeType === 'emoji_text' && flake.emojiText){
|
|
context.save();
|
|
// 設置字體大小與居中對齊 基於半徑縮放
|
|
const fontSize = Math.max(12, flake.radius * 6);
|
|
context.font = String(Math.floor(fontSize)) + 'px system-ui, Apple Color Emoji, Segoe UI Emoji, Noto Color Emoji';
|
|
context.textAlign = 'center';
|
|
context.textBaseline = 'middle';
|
|
context.fillText(String(flake.emojiText), flake.positionX, flake.positionY);
|
|
context.restore();
|
|
continue;
|
|
}
|
|
if (flake.shapeType === 'text_label' && flake.emojiText){
|
|
context.save();
|
|
const fontSize = Math.max(12, flake.radius * 5.5);
|
|
context.font = String(Math.floor(fontSize)) + 'px system-ui, -apple-system, Segoe UI, Roboto, Noto Sans';
|
|
context.textAlign = 'center';
|
|
context.textBaseline = 'middle';
|
|
context.fillStyle = 'rgba(255,255,255,0.9)';
|
|
context.fillText(String(flake.emojiText), flake.positionX, flake.positionY);
|
|
context.restore();
|
|
continue;
|
|
}
|
|
// 否则执行注册表中的形状渲染函数
|
|
const registry = window.YooneSnowShapeRenderers || {};
|
|
const renderer = registry[flake.shapeType] || registry['dot'];
|
|
// 条件判断 只有在渲染器为函数时才执行绘制
|
|
if (typeof renderer === 'function'){
|
|
renderer(context, flake.positionX, flake.positionY, flake.radius);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 清理停止函数 用于在达到设定时长后停止动画并释放资源
|
|
function cleanupStop(){
|
|
// 条件判断 如果存在窗口尺寸事件监听则移除
|
|
if (typeof onResize === 'function') {
|
|
window.removeEventListener('resize', onResize);
|
|
}
|
|
// 清空画布并隐藏元素
|
|
context.clearRect(0, 0, viewportWidth, viewportHeight);
|
|
canvas.style.display = 'none';
|
|
}
|
|
|
|
// 函数 更新系统 执行移除与补给并更新位置
|
|
function updateSystem(deltaSeconds){
|
|
for (let idx = snowflakes.length - 1; idx >= 0; idx--){
|
|
// 条件判断 仅当雪花已移出视口时才从数组移除 保证雪花下到窗口底部才消失
|
|
if (snowflakes[idx].outOfView){ snowflakes.splice(idx, 1); }
|
|
}
|
|
if (!hasReachedDuration){
|
|
// 依据当前平均速度以及视口高度估算雪花平均生命周期和补给速率
|
|
const averageVerticalSpeed = computeAverageVerticalSpeed();
|
|
const averageLifeSeconds = (viewportHeight + 5) / Math.max(0.001, averageVerticalSpeed);
|
|
const supplyRatePerSecond = snowflakesTargetCount / Math.max(0.001, averageLifeSeconds);
|
|
spawnAccumulator += supplyRatePerSecond * Math.max(0, deltaSeconds);
|
|
// 条件判断 根据累积值决定此次生成数量 保证均匀补给并确保达到最大设定数量
|
|
const availableSlots = Math.max(0, snowflakesTargetCount - snowflakes.length);
|
|
let spawnCount = Math.min(availableSlots, Math.floor(spawnAccumulator));
|
|
// 条件判断 若仍有缺口但累积量不足一整个单位 则至少补充 1 个
|
|
if (spawnCount === 0 && availableSlots > 0){ spawnCount = 1; }
|
|
// 条件判断 限制每帧最大生成数量避免瞬时爆发
|
|
const maxPerFrame = Math.max(1, Math.floor(snowflakesTargetCount * 0.05));
|
|
if (spawnCount > maxPerFrame){ spawnCount = maxPerFrame; }
|
|
if (spawnCount > 0){
|
|
spawnAccumulator = Math.max(0, spawnAccumulator - spawnCount);
|
|
for (let s = 0; s < spawnCount; s++){
|
|
const preferredX = (spawnPhase % 1) * viewportWidth;
|
|
spawnPhase = (spawnPhase + goldenRatio) % 1;
|
|
pushSnowflake(preferredX, undefined);
|
|
}
|
|
}
|
|
}
|
|
updateSnowflakes();
|
|
}
|
|
|
|
// 函数 渲染系统 清空画布并绘制
|
|
function renderSystem(){
|
|
drawSnowflakes();
|
|
}
|
|
|
|
// 函数 动画主循环 包含生成 渲染 与停止逻辑
|
|
function animate(){
|
|
const nowTs = performance.now();
|
|
const deltaSeconds = Math.max(0, (nowTs - lastUpdateTimestamp) / 1000);
|
|
lastUpdateTimestamp = nowTs;
|
|
updateSystem(deltaSeconds);
|
|
renderSystem();
|
|
// 条件判断 如果设置了有限时长则在达到时长后不再生成新粒子并等待自然落出
|
|
if (displayDurationSeconds > 0 && !hasReachedDuration){
|
|
const elapsedSeconds = (performance.now() - startTimestamp) / 1000;
|
|
if (elapsedSeconds >= displayDurationSeconds){
|
|
hasReachedDuration = true;
|
|
}
|
|
}
|
|
// 条件判断 如果已达到时长且所有粒子都移出视口则执行清理停止
|
|
if (hasReachedDuration){
|
|
const allOut = snowflakes.every(function(f){ return f.outOfView; });
|
|
if (allOut){
|
|
cleanupStop();
|
|
return;
|
|
}
|
|
}
|
|
// 调用动画循环 保持持续更新
|
|
requestAnimationFrame(animate);
|
|
}
|
|
|
|
// 定义窗口尺寸事件处理器 以便在停止时移除
|
|
function onResize(){
|
|
// 条件判断 保证画布尺寸与视口一致
|
|
resizeCanvas();
|
|
viewportWidth = window.innerWidth;
|
|
viewportHeight = window.innerHeight;
|
|
}
|
|
window.addEventListener('resize', onResize);
|
|
|
|
animate();
|
|
}
|
|
|
|
// 条件判断 如果文档尚未加载则等待 DOMContentLoaded 事件
|
|
if (document.readyState === 'loading'){
|
|
document.addEventListener('DOMContentLoaded', init);
|
|
} else {
|
|
init();
|
|
}
|
|
})();
|