You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中实现类似原生DOM的图片叠加效果(附Vencord插件TypeScript代码)

如何在React中实现类似原生DOM的图片叠加效果(附Vencord插件TypeScript代码)

嘿,我来聊聊最近开发Vencord插件时的经历——我有JavaScript中级水平,现在正在逐步上手TypeScript,这次是把一段现成的JS代码改成了TS版本,用来实现随机展示趣味图片的功能,顺便解决了类似原生DOM的图片叠加问题。下面是我的完整实现代码和思路:

/*
 * Vencord, a Discord client mod
 * Copyright (c) 2024 Vendicated and contributors
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

import { Devs } from "@utils/constants";
import definePlugin from "@utils/types";


const imgs = [
    "fruit.jpg",
    "fruit2.png",
    "wellsfargo.png",
    "goosecreakfreak.jpeg",
    "joakim.gif",
    "xsb1.gif"
];
const gitRepo = "https://codeberg.org/api/v1/repos/zav/brainrot-gallery/raw/";
const delay = ms => new Promise(res => setTimeout(res, ms));
let img: HTMLImageElement | null = null;
let interval: NodeJS.Timeout | null = null;

export default definePlugin({
    name: "brainrotGallery",
    description: "Randomly displays fun 'brainrot' images overlayed in your Discord client",
    start() {
        // 创建图片元素并设置叠加样式
        img = document.createElement("img");
        img.style.position = "fixed";
        img.style.zIndex = "9999"; // 确保图片在最上层
        img.style.top = "20px";
        img.style.left = "20px";
        img.style.width = "200px";
        img.style.height = "auto";
        img.style.borderRadius = "8px";
        img.style.boxShadow = "0 2px 10px rgba(0,0,0,0.2)";

        // 随机加载第一张图片
        const randomImg = imgs[Math.floor(Math.random() * imgs.length)];
        img.src = `${gitRepo}/main/${randomImg}`;
        document.body.appendChild(img);

        // 定时切换图片,间隔5秒
        interval = setInterval(async () => {
            if (!img) return;
            const nextImg = imgs[Math.floor(Math.random() * imgs.length)];
            img.src = `${gitRepo}/main/${nextImg}`;
            await delay(1000);
        }, 5000);
    },
    stop() {
        // 清理资源,避免内存泄漏
        if (img) {
            img.remove();
            img = null;
        }
        if (interval) {
            clearInterval(interval);
            interval = null;
        }
    },
    authors: [Devs.Zav]
});

我补充了插件的核心逻辑:在start生命周期里创建图片元素,通过设置fixed定位和高z-index实现类似原生DOM的叠加效果——让图片始终悬浮在Discord界面的最上层。用TypeScript的话,我给变量加上了类型声明(比如img: HTMLImageElement | null),这样能避免很多类型错误,代码也更健壮。

另外还完善了资源清理的逻辑,在stop方法里移除图片元素并清除定时器,防止插件卸载后还占用内存。

备注:内容来源于stack exchange,提问作者suspecting

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.16 12:35:27