跳到正文

科技·工程

luogu_ac_image 洛谷AC图片自定义!

totomac约 39 分钟
原文
文章信息与版本

文章信息

发布
2026年8月16日
收录
2026年8月17日
更新
2026年11月14日
篇幅
约 39 分钟

版本

  1. v1当前

思路

由于洛谷AC后只有一个十分单调的AC图片,比较无聊,所以我制作了一个插件,可以自定义AC图片。

设置区域

为了尽量不影响页面整体风格,面板默认隐藏,通过”更多功能”菜单中的“AC图片设置”即可打开。

参考借鉴

本插件借鉴了 a_small_OIer 的 洛谷自定义背景板 。

源代码

源代码
JavaScript
// ==UserScript==
// @name         洛谷 - AC图片自定义
// @namespace    https://www.luogu.com.cn/
// @version      1.0.0
// @description  自定义洛谷AC通过题目时的恭喜图片,支持上传或URL替换
// @author       totomac
// @license      MIT
// @match        https://www.luogu.com.cn/*
// @grant        GM_addStyle
// @grant        GM_getValue
// @grant        GM_setValue
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // === 常量 ===
    const DEFAULT_AC_IMAGE = 'http://fecdn.luogu.com.cn/luogu/ac-congrats.png';
    const DB_NAME = 'LuoguACDB';
    const DB_STORE = 'images';
    const SETTINGS_KEY = 'ac_custom_image';

    // === 设置管理 ===
    let currentImage = GM_getValue(SETTINGS_KEY, DEFAULT_AC_IMAGE);

    function saveSetting(key, value) {
        GM_setValue(key, value);
    }

    // === IndexedDB 图片存储 ===
    function openDB() {
        return new Promise((resolve, reject) => {
            const r = indexedDB.open(DB_NAME, 1);
            r.onupgradeneeded = e => {
                const db = e.target.result;
                if (!db.objectStoreNames.contains(DB_STORE)) {
                    db.createObjectStore(DB_STORE, { keyPath: 'id', autoIncrement: true });
                }
            };
            r.onsuccess = e => resolve(e.target.result);
            r.onerror = e => reject(e.target.error);
        });
    }

    async function dbAdd(item) {
        const db = await openDB();
        const tx = db.transaction(DB_STORE, 'readwrite');
        const store = tx.objectStore(DB_STORE);
        const req = store.add(item);
        return new Promise((res, rej) => {
            tx.oncomplete = () => res(req.result);
            tx.onerror = rej;
            req.onerror = rej;
        });
    }

    async function dbGet(id) {
        const db = await openDB();
        const tx = db.transaction(DB_STORE, 'readonly');
        const store = tx.objectStore(DB_STORE);
        const req = store.get(Number(id));
        return new Promise((res, rej) => {
            req.onsuccess = () => res(req.result);
            req.onerror = rej;
        });
    }

    async function dbDelete(id) {
        const db = await openDB();
        const tx = db.transaction(DB_STORE, 'readwrite');
        const store = tx.objectStore(DB_STORE);
        store.delete(Number(id));
        return new Promise((res, rej) => {
            tx.oncomplete = res;
            tx.onerror = rej;
        });
    }

    async function dbClear() {
        const db = await openDB();
        const tx = db.transaction(DB_STORE, 'readwrite');
        const store = tx.objectStore(DB_STORE);
        store.clear();
        return new Promise((res, rej) => {
            tx.oncomplete = res;
            tx.onerror = rej;
        });
    }

    async function dbAll() {
        const db = await openDB();
        const tx = db.transaction(DB_STORE, 'readonly');
        const store = tx.objectStore(DB_STORE);
        const req = store.getAll();
        return new Promise((res, rej) => {
            req.onsuccess = () => res(req.result);
            req.onerror = rej;
        });
    }

    // === 页面检测与图片替换 ===
    function findAndReplaceACImage() {
        // 只有设置了自定义图片时才替换
        if (currentImage === DEFAULT_AC_IMAGE) {
            return;
        }
        // 查找所有包含 ac-congrats 的图片并替换
        const acImages = document.querySelectorAll('img[src*="ac-congrats"]');
        acImages.forEach(img => {
            if (!img.dataset.acReplaced) {
                img.src = currentImage;
                img.dataset.acReplaced = 'true';
            }
        });
    }

    // === 样式注入 ===
    function injectStyles() {
        GM_addStyle(
            /* 设置面板 */
            "#luogu-ac-panel{position:fixed;top:50%;right:24px;z-index:99998;transform:translateY(-50%);width:320px;max-width:calc(100vw-48px);max-height:80vh;overflow-y:auto;background:rgba(255,255,255,0.97);border-radius:16px;box-shadow:0 8px 40px rgba(0,0,0,0.2);padding:20px 18px 16px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:13px;color:#333;transition:all .35s cubic-bezier(.4,0,.2,1);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px)}" +
            "#luogu-ac-panel.collapsed{opacity:0;pointer-events:none;transform:translateY(-50%) translateX(120%)}" +
            "#luogu-ac-panel h3{margin:0 0 14px;font-size:16px;font-weight:700;color:#2c3e50;text-align:center}" +
            "#luogu-ac-panel .section-title{font-size:12px;font-weight:600;color:#7f8c8d;margin:14px 0 8px;padding-top:10px;border-top:1px solid #eee;cursor:pointer;display:flex;align-items:center;justify-content:space-between}" +
            "#luogu-ac-panel .section-title:first-of-type{border-top:none;margin-top:4px;padding-top:0}" +
            "#luogu-ac-panel .section-title .arrow{transition:transform .3s;font-size:14px}" +
            "#luogu-ac-panel .section-title.collapsed .arrow{transform:rotate(-90deg)}" +
            "#luogu-ac-panel .settings-block{overflow:hidden;transition:max-height .4s ease}" +
            "#luogu-ac-panel .settings-block.collapsed{max-height:0 !important}" +
            "#luogu-ac-panel input[type=url],#luogu-ac-panel input[type=text]{width:100%;padding:8px 12px;border:1.5px solid #ddd;border-radius:8px;font-size:12px;background:#fdfdfd}" +
            "#luogu-ac-panel input:focus{outline:none;border-color:#3498db}" +
            "#luogu-ac-panel .btn-row{display:flex;gap:8px;margin-top:14px}" +
            "#luogu-ac-panel .btn-row button{flex:1;padding:9px 0;border-radius:8px;border:none;font-weight:600;cursor:pointer}" +
            "#luogu-ac-panel .btn-upload{background:#3498db;color:#fff}" +
            "#luogu-ac-panel .btn-upload:hover{background:#2980b9}" +
            "#luogu-ac-panel .btn-reset{background:#f5f5f5;color:#666;border:1px solid #ddd}" +
            "#luogu-ac-panel .btn-reset:hover{background:#e8e8e8}" +
            "#luogu-ac-panel .btn-clearall{background:#e74c3c;color:#fff}" +
            "#luogu-ac-panel .btn-clearall:hover{background:#c0392b}" +
            "#luogu-ac-panel .btn-close{width:100%;margin-top:4px;padding:8px;background:#f5f5f5;color:#888;border:1px solid #ddd;border-radius:8px;cursor:pointer}" +
            "#luogu-ac-panel .btn-close:hover{background:#e0e0e0}" +
            "#luogu-ac-panel .preview-area{text-align:center;margin:10px 0}" +
            "#luogu-ac-panel .preview-area img{max-width:100%;max-height:150px;border-radius:8px;border:1px solid #ddd}" +
            "#luogu-ac-panel .url-input-row{display:flex;gap:6px;margin-top:8px}" +
            "#luogu-ac-panel .url-input-row input{flex:1}" +
            "#luogu-ac-panel .url-input-row button{padding:8px 12px;background:#3498db;color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:12px}" +
            "#luogu-ac-panel .image-list{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}" +
            "#luogu-ac-panel .image-item{position:relative;width:50px;height:50px;border-radius:6px;overflow:hidden;border:1px solid #ddd;cursor:pointer}" +
            "#luogu-ac-panel .image-item img{width:100%;height:100%;object-fit:cover}" +
            "#luogu-ac-panel .image-item .delete-btn{position:absolute;top:0;right:0;background:rgba(231,76,60,.8);color:#fff;border:none;width:18px;height:18px;font-size:12px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:0 6px 0 6px;z-index:1}" +
            "#luogu-ac-toast{position:fixed;bottom:30px;right:30px;z-index:999999;padding:12px 20px;border-radius:8px;color:#fff;font-size:14px;box-shadow:0 4px 12px rgba(0,0,0,.2);transition:opacity .3s;opacity:0;pointer-events:none}"
        );
    }

    // === Toast 提示 ===
    let toastTimer = null;
    function showToast(message, type) {
        let el = document.getElementById('luogu-ac-toast');
        if (!el) {
            el = document.createElement('div');
            el.id = 'luogu-ac-toast';
            document.body.appendChild(el);
        }
        clearTimeout(toastTimer);
        el.textContent = message;
        if (type === 'success') {
            el.style.background = '#2ecc71';
        } else if (type === 'error') {
            el.style.background = '#e74c3c';
        } else {
            el.style.background = '#e67e22';
        }
        el.style.opacity = '1';
        toastTimer = setTimeout(() => {
            el.style.opacity = '0';
        }, 2000);
    }

    // === 文件上传 ===
    function openFilePicker() {
        const inp = document.createElement('input');
        inp.type = 'file';
        inp.accept = 'image/*';
        inp.addEventListener('change', async e => {
            const f = e.target.files[0];
            if (!f) return;
            showToast('处理中...', 'loading');
            try {
                const reader = new FileReader();
                reader.onload = ev => {
                    const img = new Image();
                    img.onload = async () => {
                        const canvas = document.createElement('canvas');
                        const MAX_SIZE = 1920;
                        let w = img.width, h = img.height;
                        if (w > MAX_SIZE || h > MAX_SIZE) {
                            if (w > h) {
                                h = Math.round(h * MAX_SIZE / w);
                                w = MAX_SIZE;
                            } else {
                                w = Math.round(w * MAX_SIZE / h);
                                h = MAX_SIZE;
                            }
                        }
                        canvas.width = w;
                        canvas.height = h;
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0, w, h);
                        const compressed = canvas.toDataURL('image/jpeg', 0.85);
                        const id = await dbAdd({ type: 'image', data: compressed, lastUsed: 0 });
                        currentImage = compressed;
                        saveSetting(SETTINGS_KEY, currentImage);
                        refreshPanel();
                        findAndReplaceACImage();
                        showToast('图片已设置', 'success');
                    };
                    img.src = ev.target.result;
                };
                reader.readAsDataURL(f);
            } catch (er) {
                console.error(er);
                showToast('处理失败', 'error');
            }
        });
        inp.click();
    }

    // === URL 添加 ===
    async function addImageUrl() {
        const input = document.getElementById('ac-url-input');
        const url = input.value.trim();
        if (!url) {
            showToast('请输入图片URL', 'error');
            return;
        }
        currentImage = url;
        saveSetting(SETTINGS_KEY, currentImage);
        input.value = '';
        refreshPanel();
        findAndReplaceACImage();
        showToast('图片URL已设置', 'success');
    }

    // === 构建面板 ===
    async function buildPanel() {
        const allMedia = await dbAll();
        const cnt = allMedia.length;
        let list = '';
        if (cnt) {
            list = allMedia.map(m => {
                return '<div class="image-item" data-id="' + m.id + '">' +
                    '<img src="' + m.data + '">' +
                    '<button class="delete-btn" data-delete="' + m.id + '">\u00d7</button>' +
                    '</div>';
            }).join('');
        }
        return '<h3>AC图片设置</h3>' +
            '<div class="preview-area">' +
            '<img id="ac-preview" src="' + currentImage + '">' +
            '</div>' +
            '<div class="section-title">上传本地图片</div>' +
            '<div class="settings-block" id="upload-block">' +
            '<button class="btn-upload" id="ac-upload-btn" style="width:100%;padding:10px;">\u2014 选择图片上传</button>' +
            '</div>' +
            '<div class="section-title collapsed" id="toggle-url">图片URL设置 <span class="arrow">\u25bc</span></div>' +
            '<div class="settings-block collapsed" id="url-block">' +
            '<div class="url-input-row">' +
            '<input type="url" id="ac-url-input" placeholder="输入图片链接地址">' +
            '<button id="ac-url-btn">设置</button>' +
            '</div>' +
            '</div>' +
            '<div class="section-title collapsed" id="toggle-history">历史图片 (' + cnt + ')</div>' +
            '<div class="settings-block collapsed" id="history-block">' +
            '<div class="image-list" id="ac-image-list">' + (list || '<span style="font-size:12px;color:#999;">暂无历史图片</span>') + '</div>' +
            '</div>' +
            '<div class="btn-row">' +
            '<button class="btn-reset" id="ac-reset">恢复默认</button>' +
            '<button class="btn-clearall" id="ac-clearall">清空历史</button>' +
            '</div>' +
            '<button class="btn-close" id="ac-close-panel">\u2715 关闭</button>';
    }

    // === 刷新面板 ===
    async function refreshPanel() {
        const list = document.getElementById('ac-image-list');
        if (!list) return;
        const allMedia = await dbAll();
        if (!allMedia.length) {
            list.innerHTML = '<span style="font-size:12px;color:#999;">暂无历史图片</span>';
            return;
        }
        list.innerHTML = allMedia.map(m => {
            return '<div class="image-item" data-id="' + m.id + '">' +
                '<img src="' + m.data + '">' +
                '<button class="delete-btn" data-delete="' + m.id + '">\u00d7</button>' +
                '</div>';
        }).join('');
        list.querySelectorAll('.image-item').forEach(item => {
            item.addEventListener('click', async e => {
                if (e.target.closest('.delete-btn')) return;
                const id = item.dataset.id;
                const m = await dbGet(id);
                if (m) {
                    currentImage = m.data;
                    saveSetting(SETTINGS_KEY, currentImage);
                    refreshPanel();
                    findAndReplaceACImage();
                    showToast('已切换图片', 'success');
                }
            });
        });
        list.querySelectorAll('.delete-btn').forEach(b => {
            b.addEventListener('click', async e => {
                e.stopPropagation();
                const id = b.dataset.delete;
                await dbDelete(id);
                refreshPanel();
                showToast('已删除', 'success');
            });
        });
        const preview = document.getElementById('ac-preview');
        if (preview) {
            preview.src = currentImage;
        }
    }

    // === 绑定事件 ===
    function bindEvents(panel) {
        panel.querySelector('#ac-upload-btn').addEventListener('click', openFilePicker);
        panel.querySelector('#ac-url-btn').addEventListener('click', addImageUrl);
        panel.querySelector('#ac-reset').addEventListener('click', async () => {
            currentImage = DEFAULT_AC_IMAGE;
            saveSetting(SETTINGS_KEY, currentImage);
            refreshPanel();
            findAndReplaceACImage();
            showToast('已恢复默认', 'success');
        });
        panel.querySelector('#ac-clearall').addEventListener('click', async () => {
            if (confirm('确定清空所有历史图片?')) {
                await dbClear();
                currentImage = DEFAULT_AC_IMAGE;
                saveSetting(SETTINGS_KEY, currentImage);
                refreshPanel();
                findAndReplaceACImage();
                showToast('已清空', 'success');
            }
        });
        panel.querySelector('#ac-close-panel').addEventListener('click', () => {
            panel.classList.add('collapsed');
        });
        const toggleUrl = panel.querySelector('#toggle-url');
        const blockUrl = panel.querySelector('#url-block');
        toggleUrl.addEventListener('click', () => {
            const c = toggleUrl.classList.toggle('collapsed');
            blockUrl.classList.toggle('collapsed', c);
        });
        const toggleHistory = panel.querySelector('#toggle-history');
        const blockHistory = panel.querySelector('#history-block');
        toggleHistory.addEventListener('click', () => {
            const c = toggleHistory.classList.toggle('collapsed');
            blockHistory.classList.toggle('collapsed', c);
        });
    }

    // === 导航栏按钮 ===
    function addNavItem() {
        const side = document.querySelector('nav.sidebar.lside');
        if (side) {
            const grp = [...side.querySelectorAll('.nav-group')].find(g =>
                g.querySelector('.group-title .title') && g.querySelector('.group-title .title').textContent.includes('更多功能')
            );
            if (grp) {
                const ul = grp.querySelector('ul');
                const ref = [...ul.children].find(li => li.textContent.includes('背景设置'));
                if (ref && !ul.querySelector('[data-ac-custom-menu]')) {
                    const li = ref.cloneNode(true);
                    li.setAttribute('data-ac-custom-menu', 'true');
                    const minorTitle = li.querySelector('.title.minor');
                    if (minorTitle) {
                        minorTitle.textContent = 'AC图片设置';
                    } else {
                        li.querySelector('.title').textContent = 'AC图片设置';
                    }
                    const a = li.querySelector('a');
                    if (a) {
                        a.removeAttribute('href');
                        a.addEventListener('click', e => {
                            e.preventDefault();
                            showPanel();
                        });
                    }
                    ul.insertBefore(li, ref);
                } else if (!ul.querySelector('[data-ac-custom-menu]')) {
                    const li = document.createElement('li');
                    li.setAttribute('data-ac-custom-menu', 'true');
                    li.innerHTML = '<a href="javascript:void(0)"><span class="title minor">AC图片设置</span></a>';
                    ul.appendChild(li);
                    li.querySelector('a').addEventListener('click', e => {
                        e.preventDefault();
                        showPanel();
                    });
                }
            }
        }
    }

    // === 显示面板 ===
    function showPanel() {
        const p = document.getElementById('luogu-ac-panel');
        if (!p) return;
        p.classList.remove('collapsed');
    }

    // === 初始化 ===
    async function init() {
        injectStyles();
        const existingPanel = document.getElementById('luogu-ac-panel');
        if (!existingPanel) {
            const panel = document.createElement('div');
            panel.id = 'luogu-ac-panel';
            panel.innerHTML = await buildPanel();
            document.body.appendChild(panel);
            bindEvents(panel);
            await refreshPanel();
        }
        addNavItem();
        new MutationObserver(addNavItem).observe(document.body, { childList: true, subtree: true });
        findAndReplaceACImage();
        new MutationObserver(findAndReplaceACImage).observe(document.body, { childList: true, subtree: true });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();

插件的开发使用 千问 辅助。

原文