canvas占位图生成器

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title> 占位图生成器 </title>
        <style>
            :root {
                --primary-color: #4361ee;
                --secondary-color: #3f37c9;
                --success-color: #4cc9f0;
                --light-color: #f8f9fa;
                --dark-color: #212529;
                --border-color: #dee2e6;
                --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                --transition: all 0.3s ease;
            }

            * {
                box-sizing: border-box;
                margin: 0;
                padding: 0;
            }

            body {
                font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                color: var(--dark-color);
                line-height: 1.6;
                padding: 20px;
                min-height: 100vh;
            }

            .container {
                max-width: 1200px;
                margin: 0 auto;
            }

            header {
                text-align: center;
                margin-bottom: 30px;
                padding: 20px;
            }

            h1 {
                font-size: 2.5rem;
                margin-bottom: 10px;
                color: var(--secondary-color);
                text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
            }

            .subtitle {
                font-size: 1.1rem;
                color: #6c757d;
            }

            .main-content {
                display: flex;
                flex-wrap: wrap;
                gap: 30px;
                margin-bottom: 30px;
            }

            @media (max-width: 768px) {
                .main-content {
                    flex-direction: column;
                }
            }

            .control-panel {
                flex: 1;
                min-width: 300px;
                background: white;
                border-radius: 10px;
                padding: 25px;
                box-shadow: var(--shadow);
            }

            .preview-panel {
                flex: 1;
                min-width: 300px;
                background: white;
                border-radius: 10px;
                padding: 25px;
                box-shadow: var(--shadow);
                display: flex;
                flex-direction: column;
            }

            .panel-title {
                font-size: 1.5rem;
                margin-bottom: 20px;
                padding-bottom: 10px;
                border-bottom: 2px solid var(--primary-color);
                color: var(--secondary-color);
            }

            .form-group {
                margin-bottom: 20px;
            }

            label {
                display: block;
                margin-bottom: 8px;
                font-weight: 500;
            }

            input[type="number"],
            input[type="text"] {
                width: 100%;
                padding: 12px;
                border: 1px solid var(--border-color);
                border-radius: 5px;
                font-size: 16px;
                transition: var(--transition);
            }

            input[type="number"]:focus,
            input[type="text"]:focus {
                outline: none;
                border-color: var(--primary-color);
                box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
            }

            .color-inputs {
                display: flex;
                gap: 15px;
            }

            .color-group {
                flex: 1;
            }

            .color-preview {
                width: 40px;
                height: 40px;
                border-radius: 5px;
                display: inline-block;
                vertical-align: middle;
                margin-left: 10px;
                border: 1px solid var(--border-color);
            }

            .btn-group {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                margin-top: 20px;
            }

            button {
                padding: 12px 20px;
                border: none;
                border-radius: 5px;
                font-size: 16px;
                font-weight: 500;
                cursor: pointer;
                transition: var(--transition);
                flex: 1;
                min-width: 120px;
            }

            .btn-primary {
                background: var(--primary-color);
                color: white;
            }

            .btn-primary:hover {
                background: var(--secondary-color);
                transform: translateY(-2px);
            }

            .btn-secondary {
                background: var(--light-color);
                color: var(--dark-color);
                border: 1px solid var(--border-color);
            }

            .btn-secondary:hover {
                background: #e9ecef;
                transform: translateY(-2px);
            }

            .btn-success {
                background: var(--success-color);
                color: white;
            }

            .btn-success:hover {
                background: #38b6ff;
                transform: translateY(-2px);
            }

            .presets {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
                gap: 10px;
                margin-top: 15px;
            }

            .preset-btn {
                padding: 8px;
                background: var(--light-color);
                border: 1px solid var(--border-color);
                border-radius: 5px;
                cursor: pointer;
                text-align: center;
                transition: var(--transition);
            }

            .preset-btn:hover {
                background: var(--primary-color);
                color: white;
            }

            .preview-container {
                flex: 1;
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 300px;
                background: #f8f9fa;
                border-radius: 5px;
                border: 1px dashed #dee2e6;
                margin-bottom: 20px;
                overflow: hidden;
            }

            #preview {
                max-width: 100%;
                max-height: 100%;
                display: none;
            }

            .placeholder-text {
                color: #6c757d;
                text-align: center;
                padding: 20px;
            }

            .action-buttons {
                display: flex;
                gap: 10px;
            }

            /* 通知容器 */
            .notifications-container {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 10000;
                width: 320px;
            }

            /* 单个通知样式 */
            .notification {
                display: flex;
                align-items: flex-start;
                padding: 16px;
                margin-bottom: 12px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                transform: translateX(100%);
                opacity: 0;
                transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
                animation: slideIn 0.3s forwards;
            }

            .notification.show {
                transform: translateX(0);
                opacity: 1;
            }

            .notification.hide {
                animation: slideOut 0.3s forwards;
            }

            @keyframes slideIn {
                from {
                    transform: translateX(100%);
                    opacity: 0;
                }
                to {
                    transform: translateX(0);
                    opacity: 1;
                }
            }

            @keyframes slideOut {
                from {
                    transform: translateX(0);
                    opacity: 1;
                }
                to {
                    transform: translateX(100%);
                    opacity: 0;
                }
            }

            /* 通知图标 */
            .notification-icon {
                margin-right: 12px;
                font-size: 20px;
                line-height: 1;
            }

            /* 通知内容 */
            .notification-content {
                flex: 1;
                font-size: 14px;
                line-height: 1.4;
            }

            /* 通知标题 */
            .notification-title {
                font-weight: 600;
                margin-bottom: 4px;
            }

            /* 通知关闭按钮 */
            .notification-close {
                background: none;
                border: none;
                cursor: pointer;
                padding: 0;
                margin-left: 12px;
                font-size: 18px;
                line-height: 1;
                opacity: 0.7;
                transition: opacity 0.2s;
            }

            .notification-close:hover {
                opacity: 1;
            }

            /* 成功通知 */
            .notification.success {
                background: #d4edda;
                color: #155724;
                border-left: 4px solid #28a745;
            }

            .notification.success .notification-icon {
                color: #28a745;
            }

            /* 错误通知 */
            .notification.error {
                background: #f8d7da;
                color: #721c24;
                border-left: 4px solid #dc3545;
            }

            .notification.error .notification-icon {
                color: #dc3545;
            }

            /* 警告通知 */
            .notification.warning {
                background: #fff3cd;
                color: #856404;
                border-left: 4px solid #ffc107;
            }

            .notification.warning .notification-icon {
                color: #ffc107;
            }

            /* 信息通知 */
            .notification.info {
                background: #d1ecf1;
                color: #0c5460;
                border-left: 4px solid #17a2b8;
            }

            .notification.info .notification-icon {
                color: #17a2b8;
            }

            footer {
                text-align: center;
                padding: 20px;
                color: #6c757d;
                font-size: 0.9rem;
            }

            .history-section {
                margin-top: 30px;
                background: white;
                border-radius: 10px;
                padding: 25px;
                box-shadow: var(--shadow);
            }

            .history-list {
                display: flex;
                flex-wrap: wrap;
                gap: 15px;
                margin-top: 15px;
            }

            .history-item {
                width: 80px;
                height: 80px;
                border: 1px solid var(--border-color);
                border-radius: 5px;
                cursor: pointer;
                transition: var(--transition);
            }

            .history-item:hover {
                transform: scale(1.05);
                box-shadow: var(--shadow);
            }

            /* 响应式设计 */
            @media (max-width: 576px) {
                .color-inputs {
                    flex-direction: column;
                    gap: 15px;
                }

                .btn-group {
                    flex-direction: column;
                }

                button {
                    width: 100%;
                }

                h1 {
                    font-size: 2rem;
                }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <header>
                <h1>Canvas 占位图生成器</h1>
                <p class="subtitle">创建自定义尺寸和样式的占位图像</p>
            </header>

            <div
                class="notifications-container"
                id="notifications-container"
            ></div>

            <div class="main-content">
                <div class="control-panel">
                    <h2 class="panel-title">1. 设置参数</h2>

                    <div class="form-group">
                        <label for="w">宽度 (px)</label>
                        <input id="w" type="number" value="600" min="1" />
                    </div>

                    <div class="form-group">
                        <label for="h">高度 (px)</label>
                        <input id="h" type="number" value="400" min="1" />
                    </div>

                    <div class="form-group">
                        <label>预设尺寸</label>
                        <div class="presets">
                            <div class="preset-btn" data-w="300" data-h="200">
                                300×200
                            </div>
                            <div class="preset-btn" data-w="600" data-h="400">
                                600×400
                            </div>
                            <div class="preset-btn" data-w="800" data-h="600">
                                800×600
                            </div>
                            <div class="preset-btn" data-w="1200" data-h="800">
                                1200×800
                            </div>
                            <div class="preset-btn" data-w="1920" data-h="1080">
                                1920×1080
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="txt">文字内容</label>
                        <input id="txt" type="text" value="600×400" />
                    </div>

                    <div class="form-group">
                        <label>颜色设置</label>
                        <div class="color-inputs">
                            <div class="color-group">
                                <label for="bg">背景色</label>
                                <input id="bg" type="color" value="#62e40c" />
                                <span
                                    class="color-preview"
                                    id="bg-preview"
                                    style="background-color: #62e40c"
                                ></span>
                            </div>

                            <div class="color-group">
                                <label for="fg">文字色</label>
                                <input id="fg" type="color" value="#333333" />
                                <span
                                    class="color-preview"
                                    id="fg-preview"
                                    style="background-color: #333333"
                                ></span>
                            </div>
                        </div>
                    </div>

                    <div class="btn-group">
                        <button id="make" class="btn-primary">
                            生成占位图
                        </button>
                        <button id="download" class="btn-secondary">
                            下载图片
                        </button>
                        <button id="base64" class="btn-secondary">
                            获取Base64
                        </button>
                    </div>
                </div>

                <div class="preview-panel">
                    <h2 class="panel-title">2. 预览结果</h2>
                    <div class="preview-container">
                        <div class="placeholder-text" id="placeholder-text">
                            点击"生成占位图"按钮创建图像
                        </div>
                        <img id="preview" alt="占位图预览" />
                    </div>
                    <div class="action-buttons">
                        <button
                            id="copy-base64"
                            class="btn-success"
                            style="display: none"
                        >
                            复制Base64到剪贴板
                        </button>
                    </div>
                </div>
            </div>

            <div class="history-section">
                <h2 class="panel-title">最近生成</h2>
                <div class="history-list" id="history-list">
                    <!-- 历史记录将在这里显示 -->
                </div>
            </div>

            <footer>
                <p>
                    Canvas 占位图生成器 &copy; 2025 | 邮箱:xvm_eht@outlook.com
                </p>
            </footer>
        </div>

        <script>
            const $ = (id) => document.getElementById(id);

            let base64;
            let history = [];

            // 更新颜色预览
            function updateColorPreview() {
                $("bg-preview").style.backgroundColor = $("bg").value;
                $("fg-preview").style.backgroundColor = $("fg").value;
            }

            // 核心:绘制 → toBlob
            function drawPlaceholder({ width, height, bg, fg, text }) {
                const canvas = document.createElement("canvas");
                canvas.width = width;
                canvas.height = height;
                const ctx = canvas.getContext("2d");

                // 背景
                ctx.fillStyle = bg;
                ctx.fillRect(0, 0, width, height);

                // 添加网格线(可选)
                ctx.strokeStyle = fg + "40"; // 半透明线条
                ctx.lineWidth = 1;

                // 绘制垂直线
                for (let x = 0; x <= width; x += 50) {
                    ctx.beginPath();
                    ctx.moveTo(x, 0);
                    ctx.lineTo(x, height);
                    ctx.stroke();
                }

                // 绘制水平线
                for (let y = 0; y <= height; y += 50) {
                    ctx.beginPath();
                    ctx.moveTo(0, y);
                    ctx.lineTo(width, y);
                    ctx.stroke();
                }

                // 文字
                ctx.fillStyle = fg;
                ctx.font = `${Math.floor(
                    Math.min(width, height) / 10
                )}px 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif`;
                ctx.textAlign = "center";
                ctx.textBaseline = "middle";

                // 添加阴影效果
                ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
                ctx.shadowBlur = 4;
                ctx.shadowOffsetX = 2;
                ctx.shadowOffsetY = 2;

                ctx.fillText(text, width / 2, height / 2);

                // 重置阴影
                ctx.shadowColor = "transparent";
                ctx.shadowBlur = 0;
                ctx.shadowOffsetX = 0;
                ctx.shadowOffsetY = 0;

                // 尺寸信息(角落)
                ctx.font = `${Math.floor(
                    Math.min(width, height) / 20
                )}px 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif`;
                ctx.textAlign = "right";
                ctx.fillText(`${width}×${height}`, width - 20, height - 20);

                // 转换为 Base64
                base64 = canvas.toDataURL("image/png");
                // 返回 Promise<Blob>
                return new Promise((resolve) =>
                    canvas.toBlob(resolve, "image/png")
                );
            }

            // 通知系统
            const NotificationManager = {
                container: null,
                counter: 0,

                init() {
                    this.container = $("notifications-container");
                    if (!this.container) {
                        const container = document.createElement("div");
                        container.className = "notifications-container";
                        container.id = "notifications-container";
                        document.body.appendChild(container);
                        this.container = container;
                    }
                },

                show(options) {
                    // 默认配置
                    const config = {
                        title: "",
                        message: "",
                        type: "info", // success, error, warning, info
                        duration: 1500,
                        closable: true,
                        ...options,
                    };

                    // 创建通知元素
                    const notification = document.createElement("div");
                    notification.className = `notification ${config.type}`;
                    notification.id = `notification-${++this.counter}`;

                    // 图标映射
                    const icons = {
                        success: "✓",
                        error: "✕",
                        warning: "⚠",
                        info: "ℹ",
                    };

                    // 构建通知内容
                    const icon = icons[config.type] || icons.info;
                    const title =
                        config.title ||
                        (config.type === "success"
                            ? "成功"
                            : config.type === "error"
                            ? "错误"
                            : config.type === "warning"
                            ? "警告"
                            : "信息");

                    notification.innerHTML = `
                        <div class="notification-icon">${icon}</div>
                        <div class="notification-content">
                            <div class="notification-title">${title}</div>
                            <div class="notification-message">${
                                config.message
                            }</div>
                        </div>
                        ${
                            config.closable
                                ? '<button class="notification-close">&times;</button>'
                                : ""
                        }
                    `;

                    // 添加到容器
                    this.container.appendChild(notification);

                    // 触发进入动画
                    setTimeout(() => {
                        notification.classList.add("show");
                    }, 10);

                    // 绑定关闭事件
                    if (config.closable) {
                        const closeBtn = notification.querySelector(
                            ".notification-close"
                        );
                        closeBtn.addEventListener("click", () => {
                            this.hide(notification);
                        });
                    }

                    // 自动关闭
                    if (config.duration > 0) {
                        setTimeout(() => {
                            this.hide(notification);
                        }, config.duration);
                    }

                    return notification;
                },

                hide(notification) {
                    if (!notification) return;

                    notification.classList.add("hide");
                    notification.classList.remove("show");

                    setTimeout(() => {
                        if (notification.parentNode) {
                            notification.parentNode.removeChild(notification);
                        }
                    }, 300);
                },

                success(message, title = "", duration = 1500) {
                    return this.show({
                        title,
                        message,
                        type: "success",
                        duration,
                    });
                },

                error(message, title = "", duration = 1500) {
                    return this.show({
                        title,
                        message,
                        type: "error",
                        duration,
                    });
                },

                warning(message, title = "", duration = 1500) {
                    return this.show({
                        title,
                        message,
                        type: "warning",
                        duration,
                    });
                },

                info(message, title = "", duration = 1500) {
                    return this.show({
                        title,
                        message,
                        type: "info",
                        duration,
                    });
                },
            };

            // 初始化通知系统
            document.addEventListener("DOMContentLoaded", () => {
                NotificationManager.init();
            });

            // 添加到历史记录
            function addToHistory(dataUrl, width, height) {
                // 添加到数组开头
                history.unshift({
                    dataUrl: dataUrl,
                    width: width,
                    height: height,
                    timestamp: new Date(),
                });

                // 限制历史记录数量
                if (history.length > 12) {
                    history.pop();
                }

                // 更新UI
                updateHistoryUI();
            }

            // 更新历史记录UI
            function updateHistoryUI() {
                const historyList = $("history-list");
                historyList.innerHTML = "";

                history.forEach((item) => {
                    const img = document.createElement("img");
                    img.src = item.dataUrl;
                    img.alt = `${item.width}×${item.height}`;
                    img.className = "history-item";
                    img.title = `${item.width}×${item.height}`;

                    img.onclick = () => {
                        $("preview").src = item.dataUrl;
                        $("preview").style.display = "block";
                        $("placeholder-text").style.display = "none";
                    };

                    historyList.appendChild(img);
                });
            }

            // 绑定事件
            document.addEventListener("DOMContentLoaded", () => {
                // 初始化颜色预览
                updateColorPreview();

                // 颜色选择器事件
                $("bg").addEventListener("input", updateColorPreview);
                $("fg").addEventListener("input", updateColorPreview);

                // 预设按钮事件
                document.querySelectorAll(".preset-btn").forEach((btn) => {
                    btn.addEventListener("click", () => {
                        const w = btn.getAttribute("data-w");
                        const h = btn.getAttribute("data-h");
                        $("w").value = w;
                        $("h").value = h;
                        $("txt").value = `${w}×${h}`;
                    });
                });

                // 生成按钮
                $("make").onclick = async () => {
                    const width = parseInt($("w").value) || 600;
                    const height = parseInt($("h").value) || 400;

                    // 限制最大尺寸
                    if (width > 5000 || height > 5000) {
                        NotificationManager.error(
                            "尺寸过大,请输入小于5000的值"
                        );
                        return;
                    }

                    const blob = await drawPlaceholder({
                        width: width,
                        height: height,
                        bg: $("bg").value,
                        fg: $("fg").value,
                        text: $("txt").value || `${width}×${height}`,
                    });

                    // 预览
                    $("preview").src = URL.createObjectURL(blob);
                    $("preview").style.display = "block";
                    $("placeholder-text").style.display = "none";

                    // 显示复制按钮
                    $("copy-base64").style.display = "block";

                    // 添加到历史记录
                    addToHistory(base64, width, height);

                    NotificationManager.success("占位图生成成功!");
                };

                // 下载按钮
                $("download").onclick = () => {
                    if (!base64) {
                        NotificationManager.error("请先生成占位图");
                        return;
                    }
                    const a = document.createElement("a");
                    a.href = base64;
                    a.download = `placeholder-${new Date().getTime()}.png`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);

                    NotificationManager.success("图片下载已开始");
                };

                // Base64按钮
                $("base64").onclick = () => {
                    if (!base64) {
                        NotificationManager.error("请先生成占位图");
                        return;
                    }
                    console.log("base64>>>", base64);
                    NotificationManager.success("Base64已输出到控制台");
                };

                // 复制Base64按钮
                $("copy-base64").onclick = async () => {
                    if (!base64) {
                        NotificationManager.error("没有可用的Base64数据");
                        return;
                    }

                    try {
                        await navigator.clipboard.writeText(base64);
                        NotificationManager.success("Base64已复制到剪贴板");
                    } catch (err) {
                        NotificationManager.error("复制失败,请手动复制");
                        console.error("复制失败:", err);
                    }
                };
            });
        </script>
    </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值