image.png
image.png

如图所示、小猫在会 睡觉、打哈欠、挠头、追踪你的鼠标。点一下睡觉都它就会起来了,别的太花哨的又不是很喜欢。目前这个小猫的实现逻辑非常灵巧。未来希望能够搞一搞它

GitHub - adryd325/oneko.js: Cat follow mouse real! A hacky script I wrote to put a cat on my site. · GitHub

基于这个仓库实现,一个 oneko.js + 一张 oneko.gif 就搞定,没有太多的交互,以后仰仗肖工帮我实现一下 摸头交互功能

可以抄我的作业如下

layouts/partials/extend_footer.html

[html] 显示已折叠代码(19 行)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
{{- $neko := site.Params.neko | default dict -}}
{{- $enabled := true -}}
{{- if isset $neko "enable" -}}
  {{- $enabled = $neko.enable -}}
{{- end -}}
{{- $onlyHome := true -}}
{{- if isset $neko "onlyHome" -}}
  {{- $onlyHome = $neko.onlyHome -}}
{{- end -}}

{{- if and $enabled (or (not $onlyHome) .IsHome) -}}
  {{- $script := resources.Get "js/neko.js" | js.Build (dict "minify" hugo.IsProduction) -}}
  {{- if not site.Params.assets.disableFingerprinting -}}
    {{- $script = $script | fingerprint -}}
<script defer crossorigin="anonymous" data-oneko-gif="/hugo-neko/oneko.gif" src="{{ $script.RelPermalink }}" integrity="{{ $script.Data.Integrity }}"></script>
  {{- else -}}
<script defer crossorigin="anonymous" data-oneko-gif="/hugo-neko/oneko.gif" src="{{ $script.RelPermalink }}"></script>
  {{- end -}}
{{- end -}}

hugo.yaml

1
2
3
  neko:
    enable: true
    onlyHome: true

assets/js

放入 neko.js

[javascript] 显示已折叠代码(322 行)
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
(function onekoHome() {
    const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
    const coarsePointer = window.matchMedia("(pointer: coarse)");
    const header = document.querySelector(".home-info .entry-header h1");

    if (prefersReducedMotion.matches || coarsePointer.matches || !header) {
        return;
    }

    let headerAnchor = header.querySelector(".oneko-title-anchor");
    if (!headerAnchor) {
        headerAnchor = document.createElement("span");
        headerAnchor.className = "oneko-title-anchor";
        headerAnchor.style.display = "inline-block";
        while (header.firstChild) {
            headerAnchor.appendChild(header.firstChild);
        }
        header.appendChild(headerAnchor);
    }

    const currentScript = document.currentScript;
    const spriteUrl =
        currentScript && currentScript.dataset.onekoGif
            ? currentScript.dataset.onekoGif
            : "/hugo-neko/oneko.gif";

    const nekoEl = document.createElement("div");
    let resizeObserver = null;
    let frameCount = 0;
    let idleTime = 0;
    let idleAnimation = "sleeping";
    let idleAnimationFrame = 0;
    let lastFrameTimestamp = 0;

    let sleeping = true;
    let justAwake = false;

    let mousePosX = 0;
    let mousePosY = 0;

    let nekoPosX = 32;
    let nekoPosY = 32;
    const nekoSpeed = 10;

    const spriteSets = {
        idle: [[-3, -3]],
        alert: [[-7, -3]],
        scratchSelf: [
            [-5, 0],
            [-6, 0],
            [-7, 0],
        ],
        scratchWallN: [
            [0, 0],
            [0, -1],
        ],
        scratchWallS: [
            [-7, -1],
            [-6, -2],
        ],
        scratchWallE: [
            [-2, -2],
            [-2, -3],
        ],
        scratchWallW: [
            [-4, 0],
            [-4, -1],
        ],
        tired: [[-3, -2]],
        sleeping: [
            [-2, 0],
            [-2, -1],
        ],
        N: [
            [-1, -2],
            [-1, -3],
        ],
        NE: [
            [0, -2],
            [0, -3],
        ],
        E: [
            [-3, 0],
            [-3, -1],
        ],
        SE: [
            [-5, -1],
            [-5, -2],
        ],
        S: [
            [-6, -3],
            [-7, -2],
        ],
        SW: [
            [-5, -3],
            [-6, -1],
        ],
        W: [
            [-4, -2],
            [-4, -3],
        ],
        NW: [
            [-1, 0],
            [-1, -1],
        ],
    };

    const clamp = (value, min, max) => Math.min(Math.max(value, min), max);

    const placeBesideHeader = () => {
        const headerRect = headerAnchor.getBoundingClientRect();
        const preferredX = headerRect.right + 10;
        const preferredY = headerRect.bottom - 24 + window.scrollY;

        nekoPosX = clamp(preferredX, 16, document.documentElement.clientWidth - 16);
        nekoPosY = Math.max(16, preferredY);

        nekoEl.style.left = `${nekoPosX - 16}px`;
        nekoEl.style.top = `${nekoPosY - 16}px`;
    };

    const setSprite = (name, frame) => {
        const sprite = spriteSets[name][frame % spriteSets[name].length];
        nekoEl.style.backgroundPosition = `${sprite[0] * 32}px ${sprite[1] * 32}px`;
    };

    const resetIdleAnimation = () => {
        idleAnimation = null;
        idleAnimationFrame = 0;
    };

    const idle = () => {
        idleTime += 1;

        if (
            idleTime > 10 &&
            Math.floor(Math.random() * 200) === 0 &&
            idleAnimation == null
        ) {
            const availableIdleAnimations = ["sleeping", "scratchSelf"];
            if (nekoPosX < 32) {
                availableIdleAnimations.push("scratchWallW");
            }
            if (nekoPosY < 32) {
                availableIdleAnimations.push("scratchWallN");
            }
            if (nekoPosX > window.innerWidth - 32) {
                availableIdleAnimations.push("scratchWallE");
            }
            if (nekoPosY > window.innerHeight - 32) {
                availableIdleAnimations.push("scratchWallS");
            }
            idleAnimation =
                availableIdleAnimations[
                    Math.floor(Math.random() * availableIdleAnimations.length)
                ];
        }

        switch (idleAnimation) {
            case "sleeping":
                if (idleAnimationFrame < 8 && !sleeping) {
                    setSprite("tired", 0);
                    break;
                }
                setSprite("sleeping", Math.floor(idleAnimationFrame / 4));
                if (idleAnimationFrame > 192 && !sleeping) {
                    resetIdleAnimation();
                }
                break;
            case "scratchWallN":
            case "scratchWallS":
            case "scratchWallE":
            case "scratchWallW":
            case "scratchSelf":
                setSprite(idleAnimation, idleAnimationFrame);
                if (idleAnimationFrame > 9) {
                    resetIdleAnimation();
                }
                break;
            default:
                setSprite("idle", 0);
                return;
        }

        idleAnimationFrame += 1;
    };

    const wakeUp = () => {
        sleeping = false;
        justAwake = true;
        idleAnimation = null;
        idleAnimationFrame = 0;
        idleTime = 999;

        nekoPosY -= window.scrollY;
        nekoPosX = clamp(nekoPosX, 16, window.innerWidth - 16);
        nekoPosY = clamp(nekoPosY, 16, window.innerHeight - 16);

        nekoEl.style.left = `${nekoPosX - 16}px`;
        nekoEl.style.top = `${nekoPosY - 16}px`;
        nekoEl.style.position = "fixed";
        nekoEl.style.pointerEvents = "none";
        nekoEl.style.cursor = "default";

        if (resizeObserver) {
            resizeObserver.disconnect();
        }
    };

    const frame = () => {
        frameCount += 1;

        const diffX = nekoPosX - mousePosX;
        const diffY = nekoPosY - mousePosY;
        const distance = Math.sqrt(diffX ** 2 + diffY ** 2);

        if (!justAwake && (distance < nekoSpeed || distance < 48 || sleeping)) {
            idle();
            return;
        }

        idleAnimation = null;
        idleAnimationFrame = 0;

        if (idleTime > 1) {
            setSprite("alert", 0);
            idleTime = Math.min(idleTime, 7);
            idleTime -= 1;
            return;
        }

        justAwake = false;

        let direction = diffY / distance > 0.5 ? "N" : "";
        direction += diffY / distance < -0.5 ? "S" : "";
        direction += diffX / distance > 0.5 ? "W" : "";
        direction += diffX / distance < -0.5 ? "E" : "";

        setSprite(direction, frameCount);

        nekoPosX -= (diffX / distance) * nekoSpeed;
        nekoPosY -= (diffY / distance) * nekoSpeed;

        nekoPosX = clamp(nekoPosX, 16, window.innerWidth - 16);
        nekoPosY = clamp(nekoPosY, 16, window.innerHeight - 16);

        nekoEl.style.left = `${nekoPosX - 16}px`;
        nekoEl.style.top = `${nekoPosY - 16}px`;
    };

    const onAnimationFrame = (timestamp) => {
        if (!nekoEl.isConnected) {
            return;
        }

        if (!lastFrameTimestamp) {
            lastFrameTimestamp = timestamp;
        }

        if (timestamp - lastFrameTimestamp > 100) {
            lastFrameTimestamp = timestamp;
            frame();
        }

        window.requestAnimationFrame(onAnimationFrame);
    };

    nekoEl.id = "oneko";
    nekoEl.ariaHidden = true;
    nekoEl.style.width = "32px";
    nekoEl.style.height = "32px";
    nekoEl.style.position = "absolute";
    nekoEl.style.backgroundImage = `url(${spriteUrl})`;
    nekoEl.style.backgroundRepeat = "no-repeat";
    nekoEl.style.imageRendering = "pixelated";
    nekoEl.style.cursor = "pointer";
    nekoEl.style.zIndex = "2147483647";

    document.body.appendChild(nekoEl);
    placeBesideHeader();

    document.addEventListener(
        "mousemove",
        (event) => {
            mousePosX = event.clientX;
            mousePosY = event.clientY;
        },
        { passive: true },
    );

    document.addEventListener(
        "scroll",
        () => {
            if (sleeping) {
                placeBesideHeader();
            }
        },
        { passive: true },
    );

    window.addEventListener(
        "resize",
        () => {
            if (sleeping) {
                placeBesideHeader();
            }
        },
        { passive: true },
    );

    if ("ResizeObserver" in window) {
        resizeObserver = new ResizeObserver(() => {
            if (sleeping) {
                placeBesideHeader();
            }
        });
        resizeObserver.observe(headerAnchor);
    }

    nekoEl.addEventListener("click", wakeUp, { once: true });
    window.requestAnimationFrame(onAnimationFrame);
})();

然后把 gif 放到 static/hugo-neko/

就这么简单。完成了