王新阳

wangxinyang

js保存剪切板中的截图

来源:deepseek

<!DOCTYPE html>
<html>
<head>
    <title>保存截图工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 2px dashed #ccc;
            padding: 20px;
            text-align: center;
            margin-top: 20px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>截图保存工具</h1>
    <p>1. 使用微信或其他截图工具截取屏幕</p>
    <p>2. 点击下方区域后按Ctrl+V(Windows)或Command+V(Mac)粘贴</p>
    <p>3. 图片将自动下载</p>
    
    <div class="container" id="pasteArea">
        点击此处后粘贴截图
    </div>

    <script>
        const pasteArea = document.getElementById('pasteArea');
        
        pasteArea.addEventListener('click', function() {
            pasteArea.textContent = '请按Ctrl+V/Command+V粘贴截图...';
            // 只添加一次性的监听器
            document.addEventListener('paste', handlePaste, { once: true });
        });

        function handlePaste(event) {
            const items = (event.clipboardData || window.clipboardData).items;
            
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf('image') !== -1) {
                    const blob = items[i].getAsFile();
                    if (blob) {
                        saveImage(blob);
                        alert('截图已保存!');
                    }
                    event.preventDefault();
                    pasteArea.textContent = '截图已处理,如需再次保存请点击此处';
                    return;
                }
            }
            
            alert('未检测到图片,请确保已复制截图图像');
            pasteArea.textContent = '截图未识别,请点击此处重试';
        }

        function saveImage(blob) {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            
            const now = new Date();
            const timestamp = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}${now.getSeconds().toString().padStart(2, '0')}`;
            a.download = `screenshot_${timestamp}.png`;
            
            document.body.appendChild(a);
            a.click();
            
            setTimeout(() => {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, 100);
        }
    </script>
</body>
</html>
2025-08-03
2025-08-30 星期六 农历七月初八