Files
giteaone 6cb65df45f effects
更新不同效果
2026-11-18 11:31:07 +08:00

2292 lines
76 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>荧光渐变互动壁纸</title>
<meta name="description" content="一款纯原生实现的荧光渐变互动壁纸:点亮实心笔画,让光沿矢量轮廓流动。">
<meta name="theme-color" content="#000000">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' fill='%23000'/%3E%3Cpath d='M32 9C33.6 25 39 30.4 55 32 39 33.6 33.6 39 32 55 30.4 39 25 33.6 9 32 25 30.4 30.4 25 32 9Z' fill='%23d9ff3f'/%3E%3C/svg%3E">
<style>
@font-face {
font-family: 'Space Grotesk';
src: url('assets/fonts/space-grotesk.woff2') format('woff2');
font-weight: 300 700;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'JetBrains Mono';
src: url('assets/fonts/jetbrains-mono.woff2') format('woff2');
font-weight: 300 600;
font-style: normal;
font-display: swap;
}
:root {
--bg: #000;
--ink: #eceadf;
--ink-rgb: 236, 234, 223;
--muted: rgba(var(--ink-rgb), 0.52);
--faint: rgba(var(--ink-rgb), 0.27);
--hair: rgba(var(--ink-rgb), 0.13);
--art-rgb: 247, 244, 234;
--art-glow-near: 0.20;
--art-glow-far: 0.07;
--a1: #d9ff3f;
--a1-rgb: 217, 255, 63;
--a2-rgb: 57, 255, 194;
--a3-rgb: 255, 79, 154;
--sans: 'Space Grotesk', 'Helvetica Neue', sans-serif;
--mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, monospace;
--cn: 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
--mark-size: min(88vw, 88vh);
--art-hover-scale: 1;
--grain-opacity: 0.045;
--ease-out: cubic-bezier(0.16, 1, 0.3, 1);
--ease-soft: cubic-bezier(0.4, 0, 0.2, 1);
}
* { box-sizing: border-box; }
html, body {
height: 100%;
margin: 0;
background: var(--bg);
color: var(--ink);
}
body {
overflow: hidden;
overscroll-behavior: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
user-select: none;
-webkit-user-select: none;
-webkit-tap-highlight-color: transparent;
}
::selection { background: var(--a1); color: #000; }
.mono {
font-family: var(--mono);
font-variant-ligatures: none;
font-size: 8px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
/* ── atmosphere ───────────────────────────────────────────── */
.ambient {
position: fixed;
inset: -12%;
z-index: 1;
pointer-events: none;
background:
radial-gradient(56% 46% at 50% 47%, rgba(190, 205, 198, 0.042), transparent 70%),
radial-gradient(80% 70% at 50% 50%, rgba(255, 255, 255, 0.012), transparent 72%);
}
.ambient .glow {
position: absolute;
border-radius: 50%;
opacity: 0;
transition: opacity 1.15s var(--ease-soft);
will-change: opacity;
}
.ambient .g1 {
left: 50%; top: 46%;
width: 78vmax; height: 62vmax;
transform: translate(-50%, -50%);
background: radial-gradient(closest-side, rgba(var(--a1-rgb), 0.12), rgba(var(--a1-rgb), 0) 72%);
}
.ambient .g2 {
left: 36%; top: 64%;
width: 58vmax; height: 48vmax;
transform: translate(-50%, -50%);
background: radial-gradient(closest-side, rgba(var(--a2-rgb), 0.10), rgba(var(--a2-rgb), 0) 72%);
}
.ambient .g3 {
left: 66%; top: 38%;
width: 48vmax; height: 42vmax;
transform: translate(-50%, -50%);
background: radial-gradient(closest-side, rgba(var(--a3-rgb), 0.075), rgba(var(--a3-rgb), 0) 72%);
}
html.is-lit .ambient .glow { opacity: 1; }
html.no-ambient .ambient .glow { display: none; }
.vignette {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
background: radial-gradient(118% 102% at 50% 45%, transparent 36%, rgba(0, 0, 0, 0.62) 100%);
}
.grain {
position: fixed;
inset: 0;
z-index: 9;
pointer-events: none;
opacity: var(--grain-opacity);
background-image: url('assets/grain.png');
background-size: 128px 128px;
mix-blend-mode: screen;
}
/* ── stage / artwork ──────────────────────────────────────── */
.stage {
position: fixed;
inset: 0;
z-index: 5;
display: grid;
place-items: center;
padding: 56px 24px 84px;
pointer-events: none;
}
.centerpiece {
display: flex;
flex-direction: column;
align-items: center;
pointer-events: none;
animation: markIn 1.5s var(--ease-out) 0.05s both;
}
.mark-wrap {
position: relative;
width: var(--mark-size);
max-width: calc(100vw - 40px);
aspect-ratio: 1500 / 1200;
pointer-events: auto;
}
/* 悬停时图形微微放大,四角限位符保持不动。
放大系数见 properties.js 的 artwork.hover_scale */
@media (hover: hover) and (pointer: fine) {
.mark-wrap:hover #mark,
.mark-wrap:hover #pixelCanvas {
transform: scale(var(--art-hover-scale));
}
}
#mark,
#pixelCanvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
transform-origin: 50% 50%;
transition: transform 0.5s var(--ease-out);
will-change: transform;
}
#mark {
overflow: visible;
touch-action: manipulation;
outline: none;
}
#mark:focus-visible {
outline: 1px dashed rgba(var(--a1-rgb), 0.55);
outline-offset: 20px;
}
#pixelCanvas {
image-rendering: pixelated;
image-rendering: crisp-edges;
opacity: 0;
visibility: hidden;
pointer-events: none;
}
.mark-wrap[data-mode='pixel'] #mark {
opacity: 0;
pointer-events: none;
}
.mark-wrap[data-mode='pixel'] #pixelCanvas {
opacity: 1;
visibility: visible;
pointer-events: auto;
}
/* ── 3Deffects:3D 跟随层 ─────────────────────────────────── */
html[data-effect='3Deffects'] .mark-wrap {
perspective: var(--tilt-persp, 1200px);
perspective-origin: 50% 50%;
}
#tiltLayer {
position: absolute;
inset: 0;
}
/* 3D 合成 hints 只在 3Deffects 下启用:preserve-3d / will-change 会让
Chromium 把 SVG 合成为纹理,导致 bounce 模式按形状命中失效。 */
html[data-effect='3Deffects'] #tiltLayer {
transform-style: preserve-3d;
will-change: transform;
}
html:not([data-effect='3Deffects']) #tiltLayer { transform: none !important; }
#tiltGlare {
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0;
mix-blend-mode: screen;
background: radial-gradient(46% 52% at var(--gx, 50%) var(--gy, 50%),
rgba(255, 255, 255, 0.9),
rgba(var(--a1-rgb), 0.35) 42%,
rgba(var(--a1-rgb), 0) 74%);
-webkit-mask-size: 100% 100%;
mask-size: 100% 100%;
-webkit-mask-repeat: no-repeat;
mask-repeat: no-repeat;
}
#tiltFloor {
position: absolute;
left: 12%;
right: 12%;
bottom: -7%;
height: 14%;
pointer-events: none;
opacity: 0;
background: radial-gradient(50% 50% at 50% 50%, rgba(var(--a1-rgb), 0.55), rgba(var(--a1-rgb), 0) 72%);
filter: blur(14px);
will-change: transform, opacity;
}
html:not([data-effect='3Deffects']) #tiltGlare,
html:not([data-effect='3Deffects']) #tiltFloor { display: none; }
html[data-effect='3Deffects']:not(.no-ambient) .ambient .glow { opacity: 0.5; }
html.fx3d-inside .bracket { border-color: rgba(var(--a1-rgb), 0.55); }
/* artwork internals */
#restArt {
cursor: pointer;
filter:
drop-shadow(0 0 5px rgba(var(--art-rgb), var(--art-glow-near)))
drop-shadow(0 0 22px rgba(var(--art-rgb), var(--art-glow-far)));
}
#hitPad {
fill: transparent;
stroke: transparent;
cursor: pointer;
stroke-linejoin: round;
touch-action: manipulation;
}
#neonWrap,
#glowGroup,
#restSheen { pointer-events: none; }
.sheen-sweep {
animation: sheen 12s linear infinite;
will-change: transform;
}
html.no-sheen .sheen-sweep {
animation: none;
display: none;
}
/* ── frame ────────────────────────────────────────────────── */
.bracket {
position: absolute;
width: 15px;
height: 15px;
border: 0 solid var(--faint);
pointer-events: none;
transition: border-color 0.7s var(--ease-soft);
}
.bracket.tl { top: -13px; left: -13px; border-top-width: 1px; border-left-width: 1px; }
.bracket.tr { top: -13px; right: -13px; border-top-width: 1px; border-right-width: 1px; }
.bracket.bl { bottom: -13px; left: -13px; border-bottom-width: 1px; border-left-width: 1px; }
.bracket.br { bottom: -13px; right: -13px; border-bottom-width: 1px; border-right-width: 1px; }
html.is-lit .bracket { border-color: rgba(var(--a1-rgb), 0.46); }
/* ── render switch ────────────────────────────────────────── */
.foot {
position: fixed;
left: 28px;
top: 50%;
bottom: auto;
transform: translateY(-50%);
z-index: 30;
display: flex;
justify-content: flex-start;
align-items: center;
pointer-events: none;
animation: footIn 0.9s var(--ease-out) 0.5s both;
}
.foot > * { pointer-events: auto; }
.mode-group {
display: flex;
align-items: center;
gap: 7px;
}
.mode {
appearance: none;
background: none;
border: 0;
margin: 0;
padding: 6px 0 7px;
font-family: var(--mono);
font-size: 9px;
letter-spacing: 0.18em;
color: var(--muted);
cursor: pointer;
position: relative;
transition: color 0.3s ease;
}
.mode::after {
content: '';
position: absolute;
left: 0;
right: 100%;
bottom: 1px;
height: 1px;
background: var(--ink);
transition: right 0.38s var(--ease-out), background-color 0.4s ease;
}
.mode[aria-pressed='true'] { color: var(--ink); }
.mode[aria-pressed='true']::after { right: 0; }
.mode:hover { color: var(--ink); }
.mode:focus-visible { outline: 1px dashed var(--faint); outline-offset: 4px; }
.mode:disabled { opacity: 0.3; cursor: not-allowed; }
.sep {
font-family: var(--mono);
font-size: 8px;
color: var(--faint);
}
/* ── artwork + effect switch(右侧竖排:PREV / NEXT / 效果切换) ── */
.side-stack {
position: fixed;
right: 28px;
top: 50%;
transform: translateY(-50%);
z-index: 30;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
animation: footIn 0.9s var(--ease-out) 0.62s both;
}
.art-switch-group {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.art-switch-group[hidden] {
display: none;
}
.fx-switch-group {
display: flex;
flex-direction: column;
align-items: center;
gap: 7px;
}
.fx-divider {
width: 22px;
height: 1px;
background: var(--hair);
margin: 2px 0 3px;
}
.fx-btn {
appearance: none;
margin: 0;
min-width: 60px;
padding: 7px 10px 8px;
background: transparent;
border: 1px solid var(--hair);
border-radius: 999px;
color: var(--muted);
font-family: var(--mono);
font-size: 8px;
letter-spacing: 0.16em;
text-indent: 0.16em;
cursor: pointer;
transition: color 0.3s ease, border-color 0.3s ease,
background-color 0.3s ease, box-shadow 0.3s ease;
}
.fx-btn:hover {
color: var(--ink);
border-color: var(--faint);
}
.fx-btn[aria-pressed='true'] {
color: var(--ink);
border-color: rgba(var(--a1-rgb), 0.5);
background: rgba(var(--a1-rgb), 0.07);
box-shadow: 0 0 14px rgba(var(--a1-rgb), 0.10);
}
.fx-btn:focus-visible {
outline: 1px dashed var(--faint);
outline-offset: 4px;
}
.fx-name {
font-size: 7px;
letter-spacing: 0.08em;
color: var(--faint);
text-transform: none;
max-width: 88px;
text-align: center;
line-height: 1.5;
overflow-wrap: break-word;
transition: color 0.4s ease;
}
.art-switch {
display: grid;
place-items: center;
width: 42px;
height: 42px;
padding: 0;
appearance: none;
background: transparent;
border: 1px solid var(--faint);
border-radius: 50%;
color: var(--muted);
font-family: var(--mono);
font-size: 9px;
letter-spacing: 0.18em;
text-indent: 0.18em;
cursor: pointer;
transition: color 0.3s ease, border-color 0.3s ease;
}
.art-switch:hover {
color: var(--ink);
border-color: var(--muted);
}
.art-switch:focus-visible {
outline: 1px dashed var(--faint);
outline-offset: 4px;
}
html.is-lit .art-switch {
border-color: rgba(var(--a1-rgb), 0.46);
}
#particles {
position: fixed;
inset: 0;
z-index: 8;
width: 100%;
height: 100%;
pointer-events: none;
}
/* ── animation ────────────────────────────────────────────── */
@keyframes markIn {
from { opacity: 0; transform: scale(0.988); }
to { opacity: 1; transform: none; }
}
@keyframes footIn {
from { opacity: 0; transform: translateY(calc(-50% + 9px)); }
to { opacity: 1; transform: translateY(-50%); }
}
@keyframes sheen {
0% { transform: translateX(-680px); }
100% { transform: translateX(1880px); }
}
/* ── responsive ───────────────────────────────────────────── */
@media (max-width: 760px) {
:root { --mark-size: min(92vw, 78vh); }
.stage { padding: 48px 16px 96px; }
.foot { left: 20px; }
.side-stack { right: 20px; }
.mode { padding: 10px 0; }
}
@media (pointer: coarse) {
#hitPad { stroke-width: 44px; }
.mode { padding: 12px 0; }
.fx-btn { padding: 10px 12px 11px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.001ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.001ms !important;
}
.sheen-sweep { display: none; }
}
</style>
</head>
<body>
<div class="ambient" aria-hidden="true">
<i class="glow g1"></i>
<i class="glow g2"></i>
<i class="glow g3"></i>
</div>
<div class="vignette" aria-hidden="true"></div>
<main class="stage">
<div class="centerpiece">
<div class="mark-wrap" id="markWrap" data-mode="vector">
<i id="tiltFloor" aria-hidden="true"></i>
<div id="tiltLayer">
<svg id="mark" viewBox="0 0 1500 1200" role="button" tabindex="0"
aria-label="荧光单色图形。点击实心笔画点亮,鼠标在笔画上停留片刻也会自动点亮一次;点击镂空处无反应。按回车键也可点亮。"
preserveAspectRatio="xMidYMid meet">
<defs>
<linearGradient id="neonGrad" gradientUnits="userSpaceOnUse" spreadMethod="reflect"
x1="0" y1="0" x2="1500" y2="0">
<stop offset="0" stop-color="#d9ff3f"/>
<stop offset="0.166" stop-color="#39ffc2"/>
<stop offset="0.333" stop-color="#3aa0ff"/>
<stop offset="0.5" stop-color="#b06bff"/>
<stop offset="0.666" stop-color="#ff4f9a"/>
<stop offset="0.833" stop-color="#ffb63f"/>
<stop offset="1" stop-color="#d9ff3f"/>
</linearGradient>
<linearGradient id="glintGrad" gradientUnits="userSpaceOnUse" spreadMethod="pad"
x1="0" y1="0" x2="820" y2="0">
<stop offset="0" stop-color="#ffffff" stop-opacity="0"/>
<stop offset="0.44" stop-color="#ffffff" stop-opacity="0"/>
<stop offset="0.485" stop-color="#ffffff" stop-opacity="0.92"/>
<stop offset="0.53" stop-color="#ffffff" stop-opacity="0.14"/>
<stop offset="0.57" stop-color="#ffffff" stop-opacity="0"/>
<stop offset="1" stop-color="#ffffff" stop-opacity="0"/>
</linearGradient>
<linearGradient id="sheenGrad" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#ffffff" stop-opacity="0"/>
<stop offset="0.42" stop-color="#ffffff" stop-opacity="0.05"/>
<stop offset="0.5" stop-color="#ffffff" stop-opacity="0.36"/>
<stop offset="0.58" stop-color="#ffffff" stop-opacity="0.05"/>
<stop offset="1" stop-color="#ffffff" stop-opacity="0"/>
</linearGradient>
<g id="glyphShapes">
<path d="M0,379.23v820.77h300v-520.77L0,379.23ZM290,1190H10.01V403.38l280,280v506.62Z"/>
<path d="M1242.9,0l-492.86,492.86L257.18,0H0v167.08h0v.02l300,300v-.02l141.07,141.07h0s231.01,231.01,231.01,231.01h155.91l134.17-134.17h0s237.83-237.83,237.83-237.83v.02l300-300v-.02h0V0h-257.1ZM1490,163.04l-280,280-17.07,17.05-369.07,369.07h-147.63l-386.22-386.22v.02L10,162.96V10h243.04l497,497L1247.04,10h242.96v153.04Z"/>
<path d="M1200,679.31v520.69h300V379.32l-300,300ZM1489.99,1190h-280v-506.54l280-280v786.54Z"/>
</g>
<clipPath id="glyphClip">
<path d="M0,379.23v820.77h300v-520.77L0,379.23ZM290,1190H10.01V403.38l280,280v506.62Z"/>
<path d="M1242.9,0l-492.86,492.86L257.18,0H0v167.08h0v.02l300,300v-.02l141.07,141.07h0s231.01,231.01,231.01,231.01h155.91l134.17-134.17h0s237.83-237.83,237.83-237.83v.02l300-300v-.02h0V0h-257.1ZM1490,163.04l-280,280-17.07,17.05-369.07,369.07h-147.63l-386.22-386.22v.02L10,162.96V10h243.04l497,497L1247.04,10h242.96v153.04Z"/>
<path d="M1200,679.31v520.69h300V379.32l-300,300ZM1489.99,1190h-280v-506.54l280-280v786.54Z"/>
</clipPath>
<mask id="floodMask" maskUnits="userSpaceOnUse" x="-1200" y="-1200" width="3900" height="3600">
<circle id="floodCircle" cx="750" cy="834" r="0" fill="#ffffff" filter="url(#floodBlur)"/>
</mask>
<filter id="floodBlur" x="-40%" y="-40%" width="180%" height="180%">
<feGaussianBlur stdDeviation="11"/>
</filter>
<filter id="glowNear" x="-40%" y="-40%" width="180%" height="180%">
<feGaussianBlur stdDeviation="6"/>
</filter>
<filter id="glowFar" x="-60%" y="-60%" width="220%" height="220%">
<feGaussianBlur stdDeviation="23"/>
</filter>
</defs>
<g id="glowGroup" opacity="0">
<use href="#glyphShapes" fill="#39ffc2" filter="url(#glowFar)" opacity="0.62"/>
<use href="#glyphShapes" fill="#d9ff3f" filter="url(#glowNear)" opacity="0.9"/>
</g>
<use id="restArt" href="#glyphShapes" fill="#f7f4ea"/>
<g id="restSheen" clip-path="url(#glyphClip)">
<g class="sheen-sweep">
<path d="M-360 -600 L-70 -600 L560 1800 L270 1800 Z" fill="url(#sheenGrad)"/>
</g>
</g>
<g id="neonWrap" opacity="0">
<g clip-path="url(#glyphClip)">
<g mask="url(#floodMask)">
<rect x="-900" y="-900" width="3300" height="3000" fill="url(#neonGrad)"/>
<rect x="-900" y="-900" width="3300" height="3000" fill="url(#glintGrad)" opacity="0.85"
style="mix-blend-mode: screen"/>
</g>
</g>
</g>
<use id="hitPad" data-hit href="#glyphShapes" fill="transparent" stroke="transparent"
pointer-events="all" stroke-width="26"/>
</svg>
<canvas id="pixelCanvas" width="180" height="144" aria-hidden="true"></canvas>
<div id="tiltGlare" aria-hidden="true"></div>
</div>
<span class="bracket tl" aria-hidden="true"></span>
<span class="bracket tr" aria-hidden="true"></span>
<span class="bracket bl" aria-hidden="true"></span>
<span class="bracket br" aria-hidden="true"></span>
</div>
</div>
</main>
<canvas id="particles" aria-hidden="true"></canvas>
<div class="grain" aria-hidden="true"></div>
<footer class="foot">
<div class="mode-group" role="group" aria-label="渲染模式">
<button class="mode" type="button" data-mode="vector" aria-pressed="true" title="矢量渐变(快捷键 V)">VECTOR</button>
<span class="sep" aria-hidden="true">/</span>
<button class="mode" type="button" data-mode="pixel" aria-pressed="false" title="像素块模式(快捷键 V)">PIXEL</button>
</div>
</footer>
<div class="side-stack">
<div class="art-switch-group" id="artSwitchGroup" role="group" aria-label="图形轮换">
<button class="art-switch" id="prevSwitch" type="button" aria-label="上一张图形" title="上一张">PREV</button>
<button class="art-switch" id="nextSwitch" type="button" aria-label="下一张图形" title="下一张">NEXT</button>
</div>
<div class="fx-switch-group" role="group" aria-label="效果切换">
<span class="fx-divider" aria-hidden="true"></span>
<button class="fx-btn" type="button" data-effect="GraduallyBounces" aria-pressed="true"
title="GraduallyBounces:点击 / 停留点亮,荧光渐层弹跳(快捷键 E 切换效果)">BOUNCE</button>
<button class="fx-btn" type="button" data-effect="3Deffects" aria-pressed="false"
title="3Deffects:限位框内鼠标驱动 3D 倾斜,转速随鼠标速度(快捷键 E 切换效果)">3D</button>
<span class="fx-name mono" id="fxName" aria-live="polite">GraduallyBounces</span>
</div>
</div>
<!-- 经典脚本(非 module):file:// 下同样可加载,共用配置、各效果配置与图库在此生效 -->
<script src="gallery.js"></script>
<script src="properties.js"></script>
<script src="effects/GraduallyBounces.js"></script>
<script src="effects/3Deffects.js"></script>
<script>
(() => {
'use strict';
/* ── fallback defaults (used only if a config file is missing) ── */
const SHARED_DEFAULTS = {
default_effect: 'GraduallyBounces',
artwork: {
render_mode: 'vector',
size: 'min(88vw, 88vh)',
color: '#f7f4ea',
opacity: 1,
pixel_resolution: 180,
pixel_threshold: 0.18,
hover_scale: 1.04
},
palette: ['#d9ff3f', '#39ffc2', '#3aa0ff', '#b06bff', '#ff4f9a', '#ffb63f']
};
const EFFECT_DEFAULTS = {
GraduallyBounces: {
effect: {
restore_ms: 3000,
fade_out_ms: 720,
flood_ms: 640,
ambient_glow: true,
rest_sheen: true,
grain_opacity: 0.045,
hover_trigger: true,
hover_delay_ms: 620,
hover_move_px: 7,
hover_ring: true
},
particles: {
enabled: true,
count: 120,
shapes: {
square: true, rectangle: true, triangle: true,
star4: true, star5: true, circle: true, ellipse: true
},
size_min: 2,
size_max: 7,
life_ms_min: 900,
life_ms_max: 2400,
rise_speed_min: 50,
rise_speed_max: 170,
spread: 0.65,
wobble: 26,
spawn_radius: 120,
glow: true
}
},
'3Deffects': {
tilt: {
max_tilt_deg: 26,
perspective_px: 1200,
min_response: 3.5,
max_response: 30,
speed_ref_px_s: 1500,
return_response: 6,
lift_px: 26,
press_depth_px: 20,
click_impulse_deg: 5,
glare: true,
glare_opacity: 0.20,
floor_glow: true,
floor_glow_opacity: 0.30,
idle_sway: true,
sway_deg: 2.2,
sway_period_ms: 9000,
ambient_glow: true,
grain_opacity: 0.045
}
}
};
const EFFECT_ORDER = ['GraduallyBounces', '3Deffects'];
const BOUNCE_ARIA = '荧光单色图形。点击实心笔画点亮,鼠标在笔画上停留片刻也会自动点亮一次;点击镂空处无反应。按回车键也可点亮。';
const TILT_ARIA = '3D 跟随图形。鼠标在四角限位框内移动时,图形朝指针方向倾斜,转速随鼠标速度;点击产生一次脉冲。按回车键也可脉冲。';
const SHAPES = ['square', 'rectangle', 'triangle', 'star4', 'star5', 'circle', 'ellipse'];
const GALLERY = Array.isArray(window.WALLPAPER_GALLERY)
? window.WALLPAPER_GALLERY.filter((a) => a && typeof a.markup === 'string' && a.markup.trim())
: [];
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const rand = (a, b) => a + Math.random() * (b - a);
const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
const mod = (n, m) => ((n % m) + m) % m;
const smoothstep = (a, b, x) => {
const t = clamp((x - a) / (b - a), 0, 1);
return t * t * (3 - 2 * t);
};
const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
const htmlEl = document.documentElement;
const motionMQ = window.matchMedia('(prefers-reduced-motion: reduce)');
const hoverMQ = window.matchMedia('(hover: hover) and (pointer: fine)');
function deepMerge(base, extra) {
const out = Array.isArray(base) ? base.slice() : Object.assign({}, base);
if (!extra || typeof extra !== 'object') return out;
for (const key of Object.keys(extra)) {
const b = base ? base[key] : undefined;
const e = extra[key];
if (e && typeof e === 'object' && !Array.isArray(e) && b && typeof b === 'object' && !Array.isArray(b)) {
out[key] = deepMerge(b, e);
} else if (e !== undefined) {
out[key] = e;
}
}
return out;
}
function num(v, fallback, min, max) {
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return clamp(n, min, max);
}
function isHex(v) {
return typeof v === 'string' && /^#[0-9a-f]{3,8}$/i.test(v.trim());
}
/* ── dom ─────────────────────────────────────────────────── */
const markSvg = document.getElementById('mark');
const markWrap = document.getElementById('markWrap');
const glyphShapes = document.getElementById('glyphShapes');
const restArt = document.getElementById('restArt');
const restSheen = document.getElementById('restSheen');
const hitPad = document.getElementById('hitPad');
const neonWrap = document.getElementById('neonWrap');
const neonGrad = document.getElementById('neonGrad');
const glintGrad = document.getElementById('glintGrad');
const glowGroup = document.getElementById('glowGroup');
const floodCircle = document.getElementById('floodCircle');
const pixelCanvas = document.getElementById('pixelCanvas');
const pixelCtx = pixelCanvas.getContext('2d');
const fxCanvas = document.getElementById('particles');
const fx = fxCanvas.getContext('2d');
const modeButtons = Array.from(document.querySelectorAll('.mode'));
const artSwitchGroup = document.getElementById('artSwitchGroup');
const prevSwitch = document.getElementById('prevSwitch');
const nextSwitch = document.getElementById('nextSwitch');
const fxButtons = Array.from(document.querySelectorAll('.fx-btn'));
const fxName = document.getElementById('fxName');
const tiltLayer = document.getElementById('tiltLayer');
const tiltGlare = document.getElementById('tiltGlare');
const tiltFloor = document.getElementById('tiltFloor');
const glowUses = Array.from(glowGroup.querySelectorAll('use'));
const neonStops = Array.from(neonGrad.querySelectorAll('stop'));
/* 3Deffects 的运行时状态(角度、速度耦合、按压、脉冲) */
const tilt = {
rx: 0, ry: 0,
nx: 0, ny: 0,
speed: 0,
inside: false,
pressed: false,
px: 0, py: 0,
lastMoveT: 0,
glareX: 50, glareY: 50,
lift: 0, press: 0, punch: 0,
kickX: 0, kickY: 0,
glare: 0
};
const state = {
baseCfg: null,
cfg: null,
effect: null,
palette: SHARED_DEFAULTS.palette.slice(),
mode: 'vector',
active: false,
fading: false,
igniteAt: 0,
lastRot: -1,
params: null,
origin: { x: 750, y: 834 },
keyPoint: { x: 750, y: 834 },
artworks: [],
artIndex: 0,
artToken: 0,
floodMax: 2200,
pixel: null,
pixelReady: false,
particles: [],
ripples: [],
raf: 0,
lastFrame: 0,
accent: SHARED_DEFAULTS.palette[0],
canHover: hoverMQ.matches,
/* 停留触发:一次连续停留只点亮一次,移开实心区域后重新武装 */
hover: {
armed: true,
charging: false,
startedAt: 0,
progress: 0,
visual: 0,
x: 0, y: 0,
ax: 0, ay: 0,
svg: null
},
reduce: motionMQ.matches
};
let fxW = 0, fxH = 0, fxDpr = 1;
const spriteCache = new Map();
const hexCache = new Map();
function hexToRgb(hex) {
if (hexCache.has(hex)) return hexCache.get(hex);
let h = hex.replace('#', '');
if (h.length === 3) h = h.split('').map((c) => c + c).join('');
const n = parseInt(h.slice(0, 6), 16);
const rgb = [(n >> 16) & 255, (n >> 8) & 255, n & 255];
hexCache.set(hex, rgb);
return rgb;
}
function rgba(hex, a) {
const [r, g, b] = hexToRgb(hex);
return `rgba(${r},${g},${b},${a})`;
}
function mixHex(a, b, t) {
const A = hexToRgb(a), B = hexToRgb(b);
const r = Math.round(A[0] + (B[0] - A[0]) * t);
const g = Math.round(A[1] + (B[1] - A[1]) * t);
const bl = Math.round(A[2] + (B[2] - A[2]) * t);
return `rgb(${r},${g},${bl})`;
}
/* ── config ──────────────────────────────────────────────── */
function sanitizeBounce(raw) {
const E = raw.effect || {};
const P = raw.particles || {};
const shapes = {};
for (const s of SHAPES) shapes[s] = (P.shapes && P.shapes[s] !== undefined) ? !!P.shapes[s] : true;
const fade = num(E.fade_out_ms, 720, 0, 8000);
const restore = num(E.restore_ms, 3000, 300, 60000);
return {
effect: {
restore_ms: restore,
fade_out_ms: Math.min(fade, restore),
flood_ms: num(E.flood_ms, 640, 40, 5000),
ambient_glow: E.ambient_glow === undefined ? true : !!E.ambient_glow,
rest_sheen: E.rest_sheen === undefined ? true : !!E.rest_sheen,
grain_opacity: num(E.grain_opacity, 0.045, 0, 0.4),
hover_trigger: E.hover_trigger === undefined ? true : !!E.hover_trigger,
hover_delay_ms: num(E.hover_delay_ms, 620, 120, 6000),
hover_move_px: num(E.hover_move_px, 7, 0, 120),
hover_ring: E.hover_ring === undefined ? true : !!E.hover_ring
},
particles: {
enabled: P.enabled === undefined ? true : !!P.enabled,
count: Math.round(num(P.count, 120, 0, 400)),
shapes,
size_min: num(P.size_min, 2, 0.5, 30),
size_max: num(P.size_max, 7, 0.6, 40),
life_ms_min: num(P.life_ms_min, 900, 100, 8000),
life_ms_max: num(P.life_ms_max, 2400, 150, 12000),
rise_speed_min: num(P.rise_speed_min, 50, 0, 1000),
rise_speed_max: num(P.rise_speed_max, 170, 1, 1400),
spread: num(P.spread, 0.65, 0, 3),
wobble: num(P.wobble, 26, 0, 200),
spawn_radius: num(P.spawn_radius, 120, 10, 600),
glow: P.glow === undefined ? true : !!P.glow
}
};
}
function sanitizeTilt(raw) {
const T = raw.tilt || {};
return {
tilt: {
max_tilt_deg: num(T.max_tilt_deg, 26, 4, 60),
perspective_px: num(T.perspective_px, 1200, 400, 3000),
min_response: num(T.min_response, 3.5, 0.5, 40),
max_response: num(T.max_response, 30, 2, 80),
speed_ref_px_s: num(T.speed_ref_px_s, 1500, 200, 6000),
return_response: num(T.return_response, 6, 0.5, 40),
lift_px: num(T.lift_px, 26, 0, 80),
press_depth_px: num(T.press_depth_px, 20, 0, 60),
click_impulse_deg: num(T.click_impulse_deg, 5, 0, 20),
glare: T.glare === undefined ? true : !!T.glare,
glare_opacity: num(T.glare_opacity, 0.20, 0, 0.6),
floor_glow: T.floor_glow === undefined ? true : !!T.floor_glow,
floor_glow_opacity: num(T.floor_glow_opacity, 0.30, 0, 0.8),
idle_sway: T.idle_sway === undefined ? true : !!T.idle_sway,
sway_deg: num(T.sway_deg, 2.2, 0, 10),
sway_period_ms: num(T.sway_period_ms, 9000, 2000, 30000),
ambient_glow: T.ambient_glow === undefined ? true : !!T.ambient_glow,
grain_opacity: num(T.grain_opacity, 0.045, 0, 0.4)
}
};
}
function loadConfig() {
/* properties.js 与 effects/*.js 通过经典 <script> 暴露全局对象,file:// 下也可读取 */
const source = (window.WALLPAPER_CONFIG
&& typeof window.WALLPAPER_CONFIG === 'object'
&& !Array.isArray(window.WALLPAPER_CONFIG))
? window.WALLPAPER_CONFIG : null;
const loaded = !!source;
const shared = deepMerge(JSON.parse(JSON.stringify(SHARED_DEFAULTS)), source);
const palette = Array.isArray(shared.palette)
? shared.palette.filter(isHex).map((c) => c.trim()).slice(0, 12)
: [];
if (palette.length < 3) palette.push(...SHARED_DEFAULTS.palette);
const A = shared.artwork || {};
const cleanSize = (typeof A.size === 'string' && A.size.length < 64 && !/[;{}<>]/.test(A.size))
? A.size : SHARED_DEFAULTS.artwork.size;
const registry = (window.WALLPAPER_EFFECTS && typeof window.WALLPAPER_EFFECTS === 'object')
? window.WALLPAPER_EFFECTS : {};
const effectSource = (id) => {
const entry = registry[id];
return (entry && typeof entry === 'object' && entry.config && typeof entry.config === 'object')
? entry.config : null;
};
const effects = {
GraduallyBounces: sanitizeBounce(deepMerge(
JSON.parse(JSON.stringify(EFFECT_DEFAULTS.GraduallyBounces)), effectSource('GraduallyBounces'))),
'3Deffects': sanitizeTilt(deepMerge(
JSON.parse(JSON.stringify(EFFECT_DEFAULTS['3Deffects'])), effectSource('3Deffects')))
};
/* 跟随速率下限不得高于上限 */
const t = effects['3Deffects'].tilt;
if (t.min_response > t.max_response) t.min_response = t.max_response;
return {
default_effect: shared.default_effect === '3Deffects' ? '3Deffects' : 'GraduallyBounces',
artwork: {
render_mode: A.render_mode === 'pixel' ? 'pixel' : 'vector',
size: cleanSize,
color: isHex(A.color) ? A.color.trim() : SHARED_DEFAULTS.artwork.color,
opacity: num(A.opacity, SHARED_DEFAULTS.artwork.opacity, 0, 1),
pixel_resolution: Math.round(num(A.pixel_resolution, 180, 32, 420)),
pixel_threshold: num(A.pixel_threshold, 0.18, 0.02, 0.9),
hover_scale: num(A.hover_scale, 1.04, 1, 1.25)
},
palette,
effects,
_loaded: loaded,
_fxLoaded: EFFECT_ORDER.filter((id) => !!effectSource(id))
};
}
/* 当前生效的配置视图:共用部分 + 当前效果的参数。
3Deffects 下点亮 / 停留 / 粒子被关闭,换成 tilt 参数。 */
function buildEffectView() {
const c = state.baseCfg;
const bounce = c.effects.GraduallyBounces;
const tiltCfg = c.effects['3Deffects'].tilt;
if (state.effect === '3Deffects') {
return {
artwork: c.artwork,
palette: c.palette,
effect: {
restore_ms: bounce.effect.restore_ms,
fade_out_ms: bounce.effect.fade_out_ms,
flood_ms: bounce.effect.flood_ms,
ambient_glow: tiltCfg.ambient_glow,
rest_sheen: false,
grain_opacity: tiltCfg.grain_opacity,
hover_trigger: false,
hover_delay_ms: bounce.effect.hover_delay_ms,
hover_move_px: bounce.effect.hover_move_px,
hover_ring: false
},
particles: Object.assign(JSON.parse(JSON.stringify(bounce.particles)), { enabled: false }),
tilt: tiltCfg,
_loaded: c._loaded
};
}
return {
artwork: c.artwork,
palette: c.palette,
effect: bounce.effect,
particles: bounce.particles,
tilt: tiltCfg,
_loaded: c._loaded
};
}
function applyConfig() {
const c = state.cfg;
state.palette = c.palette;
htmlEl.style.setProperty('--mark-size', c.artwork.size);
htmlEl.style.setProperty('--art-hover-scale', String(c.artwork.hover_scale));
htmlEl.style.setProperty('--grain-opacity', String(c.effect.grain_opacity));
htmlEl.style.setProperty('--tilt-persp', c.tilt.perspective_px + 'px');
htmlEl.classList.toggle('no-ambient', !c.effect.ambient_glow);
htmlEl.classList.toggle('no-sheen', !c.effect.rest_sheen);
const o = c.artwork.opacity;
restArt.setAttribute('fill', c.artwork.color);
restArt.style.opacity = String(o);
restSheen.style.opacity = String(o);
htmlEl.style.setProperty('--art-rgb', hexToRgb(c.artwork.color).join(','));
htmlEl.style.setProperty('--art-glow-near', String(0.2 * o));
htmlEl.style.setProperty('--art-glow-far', String(0.07 * o));
if (state.reduce) {
state.cfg.particles.count = Math.round(c.particles.count * 0.35);
}
}
function applyAccent(cols) {
const a1 = cols[0];
const a2 = cols[2 % cols.length];
const a3 = cols[4 % cols.length];
state.accent = a1;
htmlEl.style.setProperty('--a1', a1);
htmlEl.style.setProperty('--a1-rgb', hexToRgb(a1).join(','));
htmlEl.style.setProperty('--a2-rgb', hexToRgb(a2).join(','));
htmlEl.style.setProperty('--a3-rgb', hexToRgb(a3).join(','));
glowUses[0].setAttribute('fill', a2);
glowUses[1].setAttribute('fill', a1);
}
/* ── artwork gallery ─────────────────────────────────────── */
function updateArtSwitch() {
const total = state.artworks.length;
const art = state.artworks[state.artIndex];
if (artSwitchGroup) artSwitchGroup.hidden = total < 2;
if (!art) return;
const pos = `${state.artIndex + 1}/${total}`;
if (prevSwitch) {
prevSwitch.setAttribute('aria-label', `上一张图形(当前:${art.name})`);
prevSwitch.title = total > 1 ? `上一张(${pos})` : art.name;
}
if (nextSwitch) {
nextSwitch.setAttribute('aria-label', `下一张图形(当前:${art.name})`);
nextSwitch.title = total > 1 ? `下一张(${pos})` : art.name;
}
}
function paintArtwork(art) {
glyphShapes.innerHTML = art.markup;
glyphClip.innerHTML = art.markup;
state.artToken += 1;
updateGlareMask();
}
function stopLit() {
state.active = false;
state.fading = false;
state.params = null;
state.particles.length = 0;
state.ripples.length = 0;
htmlEl.classList.remove('is-lit');
neonWrap.style.transition = 'none';
neonWrap.style.opacity = '0';
glowGroup.style.transition = 'none';
glowGroup.style.opacity = '0';
floodCircle.setAttribute('r', '0');
fx.clearRect(0, 0, fxW, fxH);
}
async function setArtwork(index) {
const total = state.artworks.length;
if (!total) return;
state.artIndex = ((index % total) + total) % total;
const art = state.artworks[state.artIndex];
paintArtwork(art);
stopLit();
hoverCancel();
updateArtSwitch();
const token = state.artToken;
const ok = await buildPixelMap();
if (token !== state.artToken) return;
if (!ok) {
if (state.mode === 'pixel') setMode('vector');
return;
}
if (state.mode === 'pixel') renderPixel(performance.now(), true);
}
function setMode(mode, opts = {}) {
if (mode === 'pixel' && !state.pixel) mode = 'vector';
state.mode = mode;
markWrap.dataset.mode = mode;
hoverCancel();
for (const b of modeButtons) {
b.setAttribute('aria-pressed', String(b.dataset.mode === mode));
}
if (mode === 'pixel') {
renderPixel(performance.now());
ensureFrame();
} else {
pixelCanvas.style.cursor = 'default';
}
if (!opts.silent) {
/* the artwork's inline opacity already reflects the active state */
}
}
/* ── effect switching ────────────────────────────────────── */
const maskOK = (window.CSS && CSS.supports && (
CSS.supports('mask-image', 'url("data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22/%3E")') ||
CSS.supports('-webkit-mask-image', 'url("data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22/%3E")')
));
/* 高光只落在实心图形上:用与像素采样一致的 SVG 蒙版裁切 glare 层 */
function updateGlareMask() {
if (!maskOK) return;
const url = `url("data:image/svg+xml,${encodeURIComponent(buildMaskHtml(300, 240))}")`;
tiltGlare.style.maskImage = url;
tiltGlare.style.webkitMaskImage = url;
}
function resetTilt() {
tilt.rx = tilt.ry = 0;
tilt.nx = tilt.ny = 0;
tilt.speed = 0;
tilt.inside = false;
tilt.pressed = false;
tilt.lastMoveT = 0;
tilt.lift = tilt.press = tilt.punch = 0;
tilt.kickX = tilt.kickY = 0;
tilt.glare = 0;
htmlEl.classList.remove('fx3d-inside');
}
function setEffect(id) {
if (!EFFECT_ORDER.includes(id)) id = 'GraduallyBounces';
const changed = state.effect !== id;
state.effect = id;
htmlEl.dataset.effect = id;
if (changed) {
stopLit();
hoverCancel();
resetTilt();
}
state.cfg = buildEffectView();
applyConfig();
applyAccent(state.palette);
for (const b of fxButtons) {
b.setAttribute('aria-pressed', String(b.dataset.effect === id));
}
if (fxName) fxName.textContent = id;
markSvg.setAttribute('aria-label', id === '3Deffects' ? TILT_ARIA : BOUNCE_ARIA);
if (id === '3Deffects') {
updateGlareMask();
/* 切入时给一个小的角度冲击,让 3D 立刻可感知 */
if (changed && !state.reduce) {
tilt.kickX = -4;
tilt.kickY = 7;
}
ensureFrame();
} else {
tiltLayer.style.transform = '';
tiltGlare.style.opacity = '0';
tiltFloor.style.opacity = '0';
}
}
/* ── 3Deffects:限位框内的 3D 跟随 ───────────────────────── */
function onTiltPointerMove(e) {
if (state.effect !== '3Deffects') return;
if (e.pointerType && e.pointerType !== 'mouse' && e.pointerType !== 'pen') return;
const r = markWrap.getBoundingClientRect();
if (!r.width || !r.height) return;
const x = e.clientX;
const y = e.clientY;
const inside = x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;
const now = performance.now();
if (inside) {
if (tilt.lastMoveT && now - tilt.lastMoveT < 200) {
const dtm = Math.max(4, now - tilt.lastMoveT) / 1000;
const inst = Math.min(6000, Math.hypot(x - tilt.px, y - tilt.py) / dtm);
tilt.speed += (inst - tilt.speed) * 0.4;
}
tilt.px = x;
tilt.py = y;
tilt.lastMoveT = now;
tilt.nx = clamp((x - (r.left + r.width / 2)) / (r.width / 2), -1, 1);
tilt.ny = clamp((y - (r.top + r.height / 2)) / (r.height / 2), -1, 1);
tilt.glareX = (x - r.left) / r.width * 100;
tilt.glareY = (y - r.top) / r.height * 100;
}
if (inside !== tilt.inside) {
tilt.inside = inside;
htmlEl.classList.toggle('fx3d-inside', inside);
if (!inside) tilt.pressed = false;
}
ensureFrame();
}
function tiltLeave() {
if (state.effect !== '3Deffects') return;
if (tilt.inside) {
tilt.inside = false;
htmlEl.classList.remove('fx3d-inside');
}
tilt.pressed = false;
ensureFrame();
}
/* 点击 / 回车脉冲:涟漪 + 角度冲击 + 下压回弹 */
function tiltPulse(clientX, clientY) {
const T = state.cfg.tilt;
addRipple(clientX, clientY, state.accent);
tilt.kickX += rand(-1, 1) * T.click_impulse_deg;
tilt.kickY += rand(-1, 1) * T.click_impulse_deg;
tilt.punch = 1;
ensureFrame();
}
function onTiltPointerDown(e) {
if (state.effect !== '3Deffects') return;
if (e.button !== undefined && e.button !== 0) return;
if (!tilt.inside) return;
tilt.pressed = true;
tiltPulse(e.clientX, e.clientY);
}
function onTiltPointerUp() {
if (state.effect !== '3Deffects') return;
tilt.pressed = false;
ensureFrame();
}
function stepTilt(now, dt) {
const T = state.cfg.tilt;
/* 指针停下后速度快速衰减,跟随速率随之回落 */
if (now - tilt.lastMoveT > 120) tilt.speed *= Math.exp(-dt * 5);
let trx, tryy, lambda;
if (tilt.inside) {
trx = -T.max_tilt_deg * tilt.ny;
tryy = T.max_tilt_deg * tilt.nx;
/* 速度耦合:鼠标越快 λ 越大,转动跟进越急 */
const k = smoothstep(0, T.speed_ref_px_s, tilt.speed);
lambda = T.min_response + (T.max_response - T.min_response) * k;
} else {
if (T.idle_sway && !state.reduce) {
const ph = now / T.sway_period_ms * Math.PI * 2;
trx = Math.sin(ph * 0.8) * T.sway_deg * 0.6;
tryy = Math.sin(ph) * T.sway_deg;
} else {
trx = 0;
tryy = 0;
}
lambda = T.return_response;
}
const a = 1 - Math.exp(-lambda * dt);
tilt.rx += (trx + tilt.kickX - tilt.rx) * a;
tilt.ry += (tryy + tilt.kickY - tilt.ry) * a;
tilt.kickX *= Math.exp(-dt * 4.5);
tilt.kickY *= Math.exp(-dt * 4.5);
tilt.punch *= Math.exp(-dt * 6);
tilt.press += ((tilt.pressed ? 1 : 0) - tilt.press) * (1 - Math.exp(-dt * 16));
const liftT = tilt.inside ? T.lift_px : 0;
tilt.lift += (liftT - tilt.lift) * (1 - Math.exp(-dt * 8));
const mag = Math.min(1, Math.hypot(tilt.rx, tilt.ry) / Math.max(1, T.max_tilt_deg));
const glareOn = T.glare && maskOK;
const gT = (glareOn && tilt.inside) ? T.glare_opacity * (0.45 + 0.55 * mag) : 0;
tilt.glare += (gT - tilt.glare) * (1 - Math.exp(-dt * 10));
const z = tilt.lift - tilt.press * T.press_depth_px - tilt.punch * 12;
const sc = 1 - tilt.press * 0.018 - tilt.punch * 0.03;
tiltLayer.style.transform =
`translateZ(${z.toFixed(2)}px) rotateX(${tilt.rx.toFixed(3)}deg) rotateY(${tilt.ry.toFixed(3)}deg) scale(${sc.toFixed(4)})`;
if (glareOn) {
tiltGlare.style.opacity = tilt.glare.toFixed(3);
tiltGlare.style.setProperty('--gx', tilt.glareX.toFixed(2) + '%');
tiltGlare.style.setProperty('--gy', tilt.glareY.toFixed(2) + '%');
}
if (T.floor_glow) {
const s = 0.5 + 0.5 * (tilt.lift / Math.max(1, T.lift_px));
tiltFloor.style.opacity = (T.floor_glow_opacity * s + 0.08 * mag).toFixed(3);
tiltFloor.style.transform =
`translate(${(-tilt.ry * 1.4).toFixed(1)}px, ${(tilt.rx * 0.9 + 10).toFixed(1)}px) scale(${(1 - mag * 0.08).toFixed(3)})`;
}
}
/* 3D 效果是否还需要继续驱动帧循环 */
function tiltBusy() {
if (state.effect !== '3Deffects') return false;
const T = state.cfg.tilt;
if (T.idle_sway && !state.reduce) return true;
const rest = Math.abs(tilt.rx) < 0.03 && Math.abs(tilt.ry) < 0.03 &&
tilt.lift < 0.2 && tilt.press < 0.004 && tilt.punch < 0.004 &&
tilt.glare < 0.003 && Math.abs(tilt.kickX) < 0.03 && Math.abs(tilt.kickY) < 0.03;
return tilt.inside || tilt.pressed || !rest;
}
/* ── raster: pixel map + hit sampling ────────────────────── */
function buildMaskHtml(w, h) {
const inner = glyphShapes.innerHTML.replace(/\sfill="[^"]*"/g, '');
return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 1500 1200"><g fill="#ffffff">${inner}</g></svg>`;
}
function rasterize(w, h) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
try {
const c = document.createElement('canvas');
c.width = w; c.height = h;
const ctx = c.getContext('2d', { willReadFrequently: true });
ctx.imageSmoothingEnabled = true;
ctx.drawImage(img, 0, 0, w, h);
const data = ctx.getImageData(0, 0, w, h).data;
resolve(data);
} catch (err) {
reject(err);
}
};
img.onerror = () => reject(new Error('mask image failed'));
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(buildMaskHtml(w, h));
});
}
async function buildPixelMap() {
const cfg = state.cfg;
const W = cfg.artwork.pixel_resolution;
const H = Math.max(1, Math.round(W * 1200 / 1500));
const threshold = cfg.artwork.pixel_threshold;
const token = state.artToken;
let data;
try {
data = await rasterize(W, H);
} catch (err) {
if (token === state.artToken) {
console.warn('[wallpaper] pixel map unavailable:', err);
const pixelBtn = modeButtons.find((b) => b.dataset.mode === 'pixel');
if (pixelBtn) {
pixelBtn.disabled = true;
pixelBtn.title = '当前环境不支持像素采样';
}
}
return false;
}
/* 快速连点时丢弃已被后续图形取代的光栅结果 */
if (token !== state.artToken) return false;
const cells = [];
const solidCut = threshold * 255;
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
const a = data[(y * W + x) * 4 + 3];
if (a < solidCut) continue;
cells.push({
x, y,
a: a / 255,
ax: (x + 0.5) / W * 1500,
ay: (y + 0.5) / H * 1200,
hash: ((x * 374761393 + y * 668265263) >>> 0) % 1000 / 1000,
delay: 0
});
}
}
if (!cells.length) {
console.warn('[wallpaper] no solid pixels found');
return false;
}
/* 键盘点亮落点:离画面中心最近的实心格 */
let keyCell = cells[0];
let keyDist = Infinity;
for (const cell of cells) {
const d = (cell.ax - 750) ** 2 + (cell.ay - 600) ** 2;
if (d < keyDist) { keyDist = d; keyCell = cell; }
}
state.keyPoint = { x: keyCell.ax, y: keyCell.ay };
// rest mosaic
const rest = document.createElement('canvas');
rest.width = W; rest.height = H;
const rctx = rest.getContext('2d');
const imgData = rctx.createImageData(W, H);
const px = imgData.data;
const [baseR, baseG, baseB] = hexToRgb(cfg.artwork.color);
const artOpacity = cfg.artwork.opacity;
for (const cell of cells) {
const shade = 1 - 0.3 * (cell.y / H);
const [r, g, b] = [
Math.round(baseR * shade),
Math.round(baseG * shade),
Math.round(baseB * shade)
];
const alpha = Math.round(255 * clamp(0.34 + 0.72 * cell.a, 0, 1) * artOpacity);
const idx = (cell.y * W + cell.x) * 4;
px[idx] = r; px[idx + 1] = g; px[idx + 2] = b; px[idx + 3] = alpha;
}
rctx.putImageData(imgData, 0, 0);
pixelCanvas.width = W;
pixelCanvas.height = H;
state.pixel = { W, H, cells, rest, alpha: data };
state.pixelReady = true;
renderPixel(performance.now(), true);
return true;
}
function computePixelDelays() {
if (!state.pixel) return;
const { cells } = state.pixel;
const { x, y } = state.origin;
let max = 1;
for (const c of cells) {
const d = Math.hypot(c.ax - x, c.ay - y);
c.d = d;
if (d > max) max = d;
}
const sweep = state.cfg.effect.flood_ms * 0.88;
for (const c of cells) c.delay = (c.d / max) * sweep;
}
/* ── palette / gradient params ───────────────────────────── */
function makeParams() {
const n = state.palette.length;
let rot = (state.lastRot + 1 + Math.floor(Math.random() * Math.max(1, n - 1))) % n;
if (rot === state.lastRot) rot = (rot + 1) % n;
state.lastRot = rot;
const cols = [];
for (let i = 0; i < n; i++) cols.push(state.palette[(rot + i) % n]);
const angle = rand(0, 360);
const dir = Math.random() < 0.5 ? -1 : 1;
const phase = rand(0, 1600);
const glintPhase = Math.random();
return {
cols, rot, angle, dir, phase, glintPhase,
flowSpeed: rand(110, 230),
glintSpeed: rand(520, 800),
lut: buildLut(cols, false),
lutDim: buildLut(cols, true)
};
}
function buildLut(cols, dim) {
const out = [];
const n = 64;
for (let i = 0; i < n; i++) {
const p = i / n * cols.length;
const a = Math.floor(p) % cols.length;
const b = (a + 1) % cols.length;
const f = p - Math.floor(p);
let c = mixHex(cols[a], cols[b], f);
if (dim) {
const [r, g, bl] = c.match(/\d+/g).map(Number);
c = `rgb(${Math.round(r * 0.72)},${Math.round(g * 0.72)},${Math.round(bl * 0.72)})`;
}
out.push(c);
}
return out;
}
function setGradientLine(el, angle, len) {
const rad = angle * Math.PI / 180;
const dx = Math.cos(rad) * len / 2;
const dy = Math.sin(rad) * len / 2;
el.setAttribute('x1', (750 - dx).toFixed(2));
el.setAttribute('y1', (600 - dy).toFixed(2));
el.setAttribute('x2', (750 + dx).toFixed(2));
el.setAttribute('y2', (600 + dy).toFixed(2));
}
function configureGradient(p) {
setGradientLine(neonGrad, p.angle, 1680);
setGradientLine(glintGrad, p.angle, 820);
const base = [0, 0.16, 0.33, 0.5, 0.66, 0.84, 1];
for (let i = 0; i < neonStops.length; i++) {
let off = base[i];
if (i > 0 && i < neonStops.length - 1) {
off = clamp(off + rand(-0.022, 0.022), base[i - 1] + 0.02, base[i + 1] - 0.02);
}
neonStops[i].setAttribute('offset', off.toFixed(3));
neonStops[i].setAttribute('stop-color', p.cols[i % p.cols.length]);
}
}
/* ── ignite ──────────────────────────────────────────────── */
function toSvgPoint(clientX, clientY) {
const ctm = markSvg.getScreenCTM();
if (!ctm) return { x: 750, y: 834 };
const pt = new DOMPoint(clientX, clientY).matrixTransform(ctm.inverse());
return { x: pt.x, y: pt.y };
}
function svgToClient(x, y) {
const ctm = markSvg.getScreenCTM();
if (!ctm) {
const r = markSvg.getBoundingClientRect();
return { x: r.left + r.width / 2, y: r.top + r.height * 0.7 };
}
const pt = new DOMPoint(x, y).matrixTransform(ctm);
return { x: pt.x, y: pt.y };
}
function ignite(clientX, clientY, svgPoint) {
const now = performance.now();
const origin = svgPoint || toSvgPoint(clientX, clientY);
const p = makeParams();
/* 无论由点击、键盘还是停留触发,本次停留的机会都已用掉 */
hoverReset(false);
state.params = p;
state.origin = origin;
state.active = true;
if (state.mode === 'pixel') computePixelDelays();
state.fading = false;
state.igniteAt = now;
applyAccent(p.cols);
configureGradient(p);
const corners = [[0, 0], [1500, 0], [0, 1200], [1500, 1200]];
state.floodMax = Math.max(...corners.map(([x, y]) => Math.hypot(x - origin.x, y - origin.y))) + 80;
floodCircle.setAttribute('cx', origin.x.toFixed(2));
floodCircle.setAttribute('cy', origin.y.toFixed(2));
floodCircle.setAttribute('r', '0');
neonWrap.style.transition = 'opacity 120ms linear';
neonWrap.style.opacity = '1';
glowGroup.style.transition = 'opacity 260ms ease-out';
glowGroup.style.opacity = '1';
htmlEl.classList.add('is-lit');
const real = { x: clientX, y: clientY };
addRipple(real.x, real.y, p.cols[0]);
spawnParticles(real.x, real.y, p.cols);
ensureFrame();
}
function beginFade() {
if (state.fading) return;
state.fading = true;
const ms = state.cfg.effect.fade_out_ms;
neonWrap.style.transition = `opacity ${ms}ms cubic-bezier(0.4, 0, 0.2, 1)`;
neonWrap.style.opacity = '0';
glowGroup.style.transition = `opacity ${ms}ms cubic-bezier(0.4, 0, 0.2, 1)`;
glowGroup.style.opacity = '0';
}
function finishRestore() {
state.active = false;
state.fading = false;
htmlEl.classList.remove('is-lit');
neonWrap.style.transition = 'none';
neonWrap.style.opacity = '0';
glowGroup.style.transition = 'none';
glowGroup.style.opacity = '0';
if (state.mode === 'pixel') renderPixel(performance.now(), true);
}
/* ── hover dwell: 停留一段时间后点亮一次 ─────────────────── */
function hoverReset(armed) {
const h = state.hover;
h.charging = false;
h.progress = 0;
h.svg = null;
if (armed !== undefined) h.armed = armed;
}
/* 离开实心区域 / 失焦 / 切换:取消计时,并允许下一次停留重新触发 */
function hoverCancel() { hoverReset(true); }
function hoverTrack(clientX, clientY, svgPoint, solid) {
const h = state.hover;
const cfg = state.cfg;
if (!solid || !cfg.effect.hover_trigger || !state.canHover) {
if (h.charging || !h.armed) hoverReset(true);
return;
}
/* 本次停留已经点亮过:必须先移开再回来,避免原地反复触发 */
if (!h.armed) return;
const now = performance.now();
if (!h.charging) {
h.charging = true;
h.startedAt = now;
h.progress = 0;
h.ax = clientX;
h.ay = clientY;
ensureFrame();
} else if (Math.hypot(clientX - h.ax, clientY - h.ay) > cfg.effect.hover_move_px) {
/* 抖动容差之外视为重新停留,计时归零 */
h.startedAt = now;
h.progress = 0;
h.ax = clientX;
h.ay = clientY;
}
h.x = clientX;
h.y = clientY;
h.svg = svgPoint;
}
function fireHover() {
const h = state.hover;
const x = h.x;
const y = h.y;
const svgPoint = h.svg;
hoverReset(false);
ignite(x, y, svgPoint || undefined);
}
function stepHover(now, dt) {
const h = state.hover;
if (h.charging) {
h.progress = clamp((now - h.startedAt) / Math.max(1, state.cfg.effect.hover_delay_ms), 0, 1);
h.visual = h.progress;
if (h.progress >= 1) fireHover();
} else if (h.visual > 0) {
h.visual = Math.max(0, h.visual - dt * 4.2);
}
}
function drawHoverRing() {
const h = state.hover;
if (!state.cfg.effect.hover_ring || h.visual <= 0.004) return;
const t = h.visual;
const col = state.accent;
const ease = easeOutCubic(t);
const appear = Math.min(1, t * 7);
const r = 19 - 5 * ease;
const spr = glowSprite(col);
const gs = 46 + 30 * ease;
fx.globalAlpha = 0.17 * appear * (0.35 + 0.65 * t);
fx.drawImage(spr, h.x - gs / 2, h.y - gs / 2, gs, gs);
fx.globalAlpha = 1;
fx.lineCap = 'round';
fx.beginPath();
fx.arc(h.x, h.y, r, 0, Math.PI * 2);
fx.strokeStyle = rgba(col, 0.14 * appear);
fx.lineWidth = 1;
fx.stroke();
fx.beginPath();
fx.arc(h.x, h.y, r, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * t);
fx.strokeStyle = rgba(col, (0.42 + 0.5 * t) * appear);
fx.lineWidth = 1.7;
fx.stroke();
fx.beginPath();
fx.arc(h.x, h.y, 1.5 + 1.1 * ease, 0, Math.PI * 2);
fx.fillStyle = rgba(col, (0.3 + 0.55 * t) * appear);
fx.fill();
fx.lineCap = 'butt';
}
/* ── fx: ripples + particles ─────────────────────────────── */
function resizeFx() {
fxDpr = Math.min(2, window.devicePixelRatio || 1);
fxW = window.innerWidth;
fxH = window.innerHeight;
fxCanvas.width = Math.round(fxW * fxDpr);
fxCanvas.height = Math.round(fxH * fxDpr);
fxCanvas.style.width = fxW + 'px';
fxCanvas.style.height = fxH + 'px';
fx.setTransform(fxDpr, 0, 0, fxDpr, 0, 0);
}
function glowSprite(color) {
if (spriteCache.has(color)) return spriteCache.get(color);
const size = 64;
const c = document.createElement('canvas');
c.width = c.height = size;
const g = c.getContext('2d');
const grad = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
grad.addColorStop(0, rgba(color, 0.85));
grad.addColorStop(0.28, rgba(color, 0.32));
grad.addColorStop(1, rgba(color, 0));
g.fillStyle = grad;
g.fillRect(0, 0, size, size);
spriteCache.set(color, c);
return c;
}
function cellToClient(cell) {
/* 用 canvas 而不是 markWrap 的包围盒:hover 放大作用于图形本身,
canvas 的矩形会同步缩放,粒子落点才能贴合静置图形 */
const r = pixelCanvas.getBoundingClientRect();
return {
x: r.left + (cell.x + 0.5) / state.pixel.W * r.width,
y: r.top + (cell.y + 0.5) / state.pixel.H * r.height
};
}
function spawnParticles(clientX, clientY, cols) {
const cfg = state.cfg;
if (!cfg.particles.enabled) return;
const enabled = SHAPES.filter((s) => cfg.particles.shapes[s]);
if (!enabled.length) return;
let near = [];
let all = [];
if (state.pixel && state.pixelReady) {
all = state.pixel.cells.map(cellToClient);
const r2 = cfg.particles.spawn_radius * cfg.particles.spawn_radius;
near = [];
for (let i = 0; i < state.pixel.cells.length; i++) {
const pt = all[i];
const dx = pt.x - clientX;
const dy = pt.y - clientY;
if (dx * dx + dy * dy <= r2) near.push(pt);
}
}
if (!near.length) near = null;
if (!all.length) all = null;
const count = cfg.particles.count;
const now = performance.now();
for (let i = 0; i < count; i++) {
const useGlobal = all && (!near || Math.random() < 0.26);
const pt = useGlobal ? pick(all) : (near ? pick(near) : { x: clientX, y: clientY });
const up = rand(cfg.particles.rise_speed_min, cfg.particles.rise_speed_max);
const shape = pick(enabled);
const isShape = shape !== 'circle';
let color;
if (Math.random() < 0.08) color = '#f5f1e7';
else color = pick(cols);
state.particles.push({
x: pt.x + rand(-2.5, 2.5),
y: pt.y + rand(-2, 2),
vx: rand(-1, 1) * up * cfg.particles.spread * 0.55,
vy: -up * rand(0.72, 1.28),
size: rand(cfg.particles.size_min, cfg.particles.size_max),
shape,
color,
alpha: rand(0.5, 0.95),
rot: rand(0, Math.PI * 2),
vr: isShape ? rand(-2.6, 2.6) : 0,
wobble: cfg.particles.wobble * rand(0.35, 1),
freq: rand(0.8, 2.6),
phase: rand(0, Math.PI * 2),
life: rand(cfg.particles.life_ms_min, cfg.particles.life_ms_max),
delay: rand(0, 0.3),
age: 0,
started: false,
born: now
});
}
if (state.particles.length > 900) {
state.particles.splice(0, state.particles.length - 900);
}
}
function addRipple(x, y, color) {
state.ripples.push({ x, y, color, age: 0, dur: 640 });
}
function stepFx(dt) {
const parts = state.particles;
for (let i = parts.length - 1; i >= 0; i--) {
const p = parts[i];
if (!p.started) {
p.delay -= dt;
if (p.delay > 0) continue;
p.started = true;
}
p.age += dt * 1000;
if (p.age >= p.life) { parts.splice(i, 1); continue; }
p.vy -= 11 * dt;
p.vx *= Math.pow(0.58, dt);
p.x += (p.vx + Math.sin(p.age * 0.004 * p.freq + p.phase) * p.wobble) * dt;
p.y += p.vy * dt;
p.rot += p.vr * dt;
if (p.y < -100 || p.y > fxH + 100 || p.x < -100 || p.x > fxW + 100) {
parts.splice(i, 1);
}
}
for (let i = state.ripples.length - 1; i >= 0; i--) {
const r = state.ripples[i];
r.age += dt * 1000;
if (r.age >= r.dur) state.ripples.splice(i, 1);
}
}
function pathStar(ctx, outer, inner, points) {
for (let i = 0; i < points * 2; i++) {
const r = i % 2 === 0 ? outer : inner;
const a = (i * Math.PI / points) - Math.PI / 2;
const x = Math.cos(a) * r;
const y = Math.sin(a) * r;
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
}
ctx.closePath();
}
function traceShape(p, scale) {
const s = p.size * scale;
fx.beginPath();
switch (p.shape) {
case 'square':
fx.rect(-s / 2, -s / 2, s, s);
break;
case 'rectangle':
fx.rect(-s * 0.88, -s * 0.31, s * 1.76, s * 0.62);
break;
case 'triangle':
fx.moveTo(0, -s * 0.62);
fx.lineTo(s * 0.6, s * 0.4);
fx.lineTo(-s * 0.6, s * 0.4);
fx.closePath();
break;
case 'star4':
pathStar(fx, s * 0.9, s * 0.21, 4);
break;
case 'star5':
pathStar(fx, s * 0.66, s * 0.28, 5);
break;
case 'ellipse':
fx.ellipse(0, 0, s * 0.66, s * 0.3, 0, 0, Math.PI * 2);
break;
case 'circle':
default:
fx.arc(0, 0, s * 0.5, 0, Math.PI * 2);
break;
}
}
function drawFx() {
fx.clearRect(0, 0, fxW, fxH);
fx.globalCompositeOperation = 'lighter';
for (const r of state.ripples) {
const t = r.age / r.dur;
const radius = 10 + easeOutCubic(t) * 76;
const alpha = Math.pow(1 - t, 2) * 0.55;
fx.beginPath();
fx.arc(r.x, r.y, radius, 0, Math.PI * 2);
fx.strokeStyle = rgba(r.color, alpha);
fx.lineWidth = 1.4 * (1 - t) + 0.2;
fx.stroke();
const spr = glowSprite(r.color);
const s = 54 + t * 70;
fx.globalAlpha = Math.pow(1 - t, 2.2) * 0.7;
fx.drawImage(spr, r.x - s / 2, r.y - s / 2, s, s);
fx.globalAlpha = 1;
}
drawHoverRing();
const glowOn = state.cfg && state.cfg.particles.glow;
for (const p of state.particles) {
if (!p.started) continue;
const t = p.age / p.life;
const fade = Math.min(1, t / 0.075) * (1 - smoothstep(0.62, 1, t));
const alpha = p.alpha * fade;
if (alpha <= 0.01) continue;
const scale = 1 - 0.18 * t * t;
if (glowOn) {
const spr = glowSprite(p.color);
const s = p.size * (5.4 * scale);
fx.globalAlpha = alpha * 0.4;
fx.drawImage(spr, p.x - s / 2, p.y - s / 2, s, s);
}
fx.save();
fx.translate(p.x, p.y);
fx.rotate(p.rot);
fx.fillStyle = p.color;
fx.globalAlpha = alpha;
traceShape(p, scale);
fx.fill();
fx.restore();
}
fx.globalAlpha = 1;
fx.globalCompositeOperation = 'source-over';
}
/* ── pixel renderer ─────────────────────────────────────── */
function renderPixel(now, forceRest = false) {
if (!state.pixel || state.mode !== 'pixel') return;
const { W, H, cells, rest } = state.pixel;
const ctx = pixelCtx;
ctx.clearRect(0, 0, W, H);
ctx.drawImage(rest, 0, 0);
if (forceRest || !state.active) return;
const cfg = state.cfg;
const elapsed = now - state.igniteAt;
const fadeStart = cfg.effect.restore_ms - cfg.effect.fade_out_ms;
let alpha = 1;
if (elapsed > fadeStart) {
alpha = clamp(1 - (elapsed - fadeStart) / Math.max(1, cfg.effect.fade_out_ms), 0, 1);
}
if (alpha <= 0) return;
const p = state.params;
const rad = p.angle * Math.PI / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
const flow = mod((p.phase / 1600) + p.dir * elapsed / 1000 * 0.08, 1);
ctx.globalAlpha = alpha;
for (const c of cells) {
if (elapsed < c.delay) continue;
const nx = c.ax / 1500;
const ny = c.ay / 1200;
const idx = Math.floor(mod(nx * cos + ny * sin + flow, 1) * 63);
let color = p.lut[idx];
const shimmer = Math.sin(elapsed * 0.0045 + c.hash * 6.283);
if (shimmer < -0.7) color = p.lutDim[idx];
if (elapsed - c.delay < 90) color = '#ffffff';
ctx.fillStyle = color;
ctx.fillRect(c.x, c.y, 1, 1);
}
ctx.globalAlpha = 1;
}
function pixelPointToCell(clientX, clientY) {
if (!state.pixel) return null;
const r = pixelCanvas.getBoundingClientRect();
if (!r.width || !r.height) return null;
const nx = (clientX - r.left) / r.width;
const ny = (clientY - r.top) / r.height;
if (nx < 0 || nx > 1 || ny < 0 || ny > 1) return null;
const { W, H, cells } = state.pixel;
const gx = Math.floor(nx * W);
const gy = Math.floor(ny * H);
// direct alpha test from the raster
return { gx, gy, r, nx, ny };
}
function isSolidPixel(gx, gy) {
const c = state.pixel;
if (!c) return false;
if (!c.alpha) return false;
const i = (gy * c.W + gx) * 4 + 3;
return c.alpha[i] > state.cfg.artwork.pixel_threshold * 255;
}
/* ── main loop ───────────────────────────────────────────── */
function ensureFrame() {
if (!state.raf) {
state.raf = requestAnimationFrame(frame);
}
}
function frame(now) {
state.raf = 0;
if (!state.lastFrame) state.lastFrame = now;
const dt = Math.min(0.05, (now - state.lastFrame) / 1000);
state.lastFrame = now;
if (state.active) {
const elapsed = now - state.igniteAt;
const cfg = state.cfg;
const fp = clamp(elapsed / Math.max(40, cfg.effect.flood_ms), 0, 1);
floodCircle.setAttribute('r', (state.floodMax * easeOutCubic(fp)).toFixed(1));
const p = state.params;
const rad = p.angle * Math.PI / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
const off = mod(p.phase + p.dir * p.flowSpeed * elapsed / 1000, 1680);
neonGrad.setAttribute('gradientTransform', `translate(${(cos * off).toFixed(2)} ${(sin * off).toFixed(2)})`);
const gOff = mod(p.glintPhase * 820 + p.dir * p.glintSpeed * elapsed / 1000, 1640) - 820;
glintGrad.setAttribute('gradientTransform', `translate(${(cos * gOff).toFixed(2)} ${(sin * gOff).toFixed(2)})`);
if (state.mode === 'pixel') {
if (now - (state.lastPixelDraw || 0) > 32) {
state.lastPixelDraw = now;
renderPixel(now);
}
}
if (elapsed >= cfg.effect.restore_ms - cfg.effect.fade_out_ms) beginFade();
if (elapsed >= cfg.effect.restore_ms) finishRestore();
}
stepHover(now, dt);
if (state.effect === '3Deffects') stepTilt(now, dt);
stepFx(dt);
drawFx();
const h = state.hover;
if (state.active || state.particles.length || state.ripples.length || h.charging || h.visual > 0.004 || tiltBusy()) {
ensureFrame();
} else {
state.lastFrame = 0;
if (state.mode === 'pixel') renderPixel(now, true);
}
}
/* ── events ──────────────────────────────────────────────── */
function solidTarget(e) {
const t = e.target;
if (!t || !t.closest) return false;
return !!t.closest('[data-hit]');
}
function onMarkClick(e) {
if (state.effect === '3Deffects') return; /* 3D 模式的点击反馈在 pointerdown 脉冲里 */
if (state.mode !== 'vector') return;
if (!solidTarget(e)) return;
ignite(e.clientX, e.clientY);
}
/* 停留触发只响应真正的悬停指针(鼠标 / 触控笔),触摸拖动不算 */
function hoverPointer(e) {
return !e.pointerType || e.pointerType === 'mouse' || e.pointerType === 'pen';
}
function onMarkMove(e) {
if (state.effect === '3Deffects') return;
if (state.mode !== 'vector' || !hoverPointer(e)) return;
const solid = solidTarget(e);
hoverTrack(e.clientX, e.clientY, solid ? toSvgPoint(e.clientX, e.clientY) : null, solid);
}
function onMarkKey(e) {
if (e.key !== 'Enter' && e.key !== ' ') return;
e.preventDefault();
if (state.effect === '3Deffects') {
const r = markWrap.getBoundingClientRect();
tiltPulse(r.left + r.width / 2, r.top + r.height / 2);
return;
}
if (state.mode !== 'vector') return;
const kp = state.keyPoint;
const pt = svgToClient(kp.x, kp.y);
ignite(pt.x, pt.y, { x: kp.x, y: kp.y });
}
function onPixelClick(e) {
if (state.effect === '3Deffects') return;
if (state.mode !== 'pixel') return;
const loc = pixelPointToCell(e.clientX, e.clientY);
if (!loc) return;
if (!isSolidPixel(loc.gx, loc.gy)) return;
const svgPt = toSvgPoint(e.clientX, e.clientY);
ignite(e.clientX, e.clientY, svgPt);
}
function onPixelMove(e) {
if (state.mode !== 'pixel') return;
const loc = pixelPointToCell(e.clientX, e.clientY);
const solid = !!(loc && isSolidPixel(loc.gx, loc.gy));
pixelCanvas.style.cursor = solid ? 'pointer' : 'default';
if (!hoverPointer(e)) return;
hoverTrack(e.clientX, e.clientY, solid ? toSvgPoint(e.clientX, e.clientY) : null, solid);
}
function onKeyDown(e) {
if (e.metaKey || e.ctrlKey || e.altKey) return;
if (e.key === 'v' || e.key === 'V') {
setMode(state.mode === 'vector' ? 'pixel' : 'vector');
} else if (e.key === 'e' || e.key === 'E') {
const i = EFFECT_ORDER.indexOf(state.effect);
setEffect(EFFECT_ORDER[(i + 1) % EFFECT_ORDER.length]);
}
}
let resizeTimer = 0;
function onResize() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
resizeFx();
hoverCancel();
if (state.mode === 'pixel') renderPixel(performance.now(), !state.active);
}, 120);
}
function bind() {
markSvg.addEventListener('click', onMarkClick);
markSvg.addEventListener('keydown', onMarkKey);
markSvg.addEventListener('pointermove', onMarkMove);
markSvg.addEventListener('pointerleave', hoverCancel);
markSvg.addEventListener('pointerdown', hoverCancel);
pixelCanvas.addEventListener('click', onPixelClick);
pixelCanvas.addEventListener('pointermove', onPixelMove);
pixelCanvas.addEventListener('pointerdown', hoverCancel);
pixelCanvas.addEventListener('pointerleave', () => {
pixelCanvas.style.cursor = 'default';
hoverCancel();
});
for (const b of modeButtons) {
b.addEventListener('click', () => {
if (b.dataset.mode === 'pixel' && !state.pixel) return;
setMode(b.dataset.mode);
});
}
if (prevSwitch) {
prevSwitch.addEventListener('click', () => setArtwork(state.artIndex - 1));
}
if (nextSwitch) {
nextSwitch.addEventListener('click', () => setArtwork(state.artIndex + 1));
}
for (const b of fxButtons) {
b.addEventListener('click', () => setEffect(b.dataset.effect));
}
window.addEventListener('pointermove', onTiltPointerMove, { passive: true });
window.addEventListener('pointerdown', onTiltPointerDown);
window.addEventListener('pointerup', onTiltPointerUp);
window.addEventListener('pointercancel', onTiltPointerUp);
window.addEventListener('keydown', onKeyDown);
window.addEventListener('resize', onResize);
window.addEventListener('blur', () => { hoverCancel(); tiltLeave(); });
document.addEventListener('mouseleave', () => { hoverCancel(); tiltLeave(); });
document.addEventListener('visibilitychange', () => {
if (document.hidden) { hoverCancel(); tiltLeave(); }
});
hoverMQ.addEventListener?.('change', (e) => {
state.canHover = e.matches;
if (!e.matches) hoverCancel();
});
motionMQ.addEventListener?.('change', (e) => {
state.reduce = e.matches;
state.cfg.particles.count = e.matches
? Math.round(EFFECT_DEFAULTS.GraduallyBounces.particles.count * 0.35)
: state.cfg.particles.count;
ensureFrame();
});
}
/* ── boot ────────────────────────────────────────────────── */
async function init() {
resizeFx();
state.baseCfg = loadConfig();
setEffect(state.baseCfg.default_effect);
bind();
state.artworks = GALLERY;
if (state.artworks.length) {
state.artIndex = 0;
paintArtwork(state.artworks[0]);
}
updateArtSwitch();
await buildPixelMap();
if (state.baseCfg._loaded) {
console.info('[wallpaper] properties.js loaded');
} else {
console.info('[wallpaper] using embedded defaults (properties.js not found)');
}
const fxLoaded = state.baseCfg._fxLoaded;
if (fxLoaded.length === EFFECT_ORDER.length) {
console.info('[wallpaper] effect configs loaded:', fxLoaded.join(', '));
} else {
const missing = EFFECT_ORDER.filter((id) => !fxLoaded.includes(id));
console.info('[wallpaper] effect configs missing, using embedded defaults:', missing.join(', '));
}
setMode(state.cfg.artwork.render_mode, { silent: true });
requestAnimationFrame(() => {
requestAnimationFrame(() => htmlEl.classList.add('is-ready'));
});
}
init();
})();
</script>
</body>
</html>