H5视频播放器截图工具

适用于所有H5播放器的截图脚本,快捷键Alt+1

当前为 2025-07-14 提交的版本,查看 最新版本

// ==UserScript==
// @name         H5视频播放器截图工具
// @version      2025.07.14.3
// @description  适用于所有H5播放器的截图脚本,快捷键Alt+1
// @author       嘉友友
// @match        *://www.youtube.com/*
// @match        *://www.bilibili.com/*
// @license      GPL-3.0
// @namespace https://greasyfork.org/users/1336389
// ==/UserScript==


(function() {
    'use strict';

    // 创建截图功能
    function captureVideoFrame() {
        // 查找页面中的视频元素
        const videos = document.querySelectorAll('video');
        
        if (videos.length === 0) {
            alert('未找到视频播放器!');
            return;
        }

        // 选择第一个可见的视频元素
        let targetVideo = null;
        for (let video of videos) {
            const rect = video.getBoundingClientRect();
            if (rect.width > 0 && rect.height > 0 && !video.hidden) {
                targetVideo = video;
                break;
            }
        }

        if (!targetVideo) {
            alert('未找到正在播放的视频!');
            return;
        }

        try {
            // 创建canvas元素
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            // 设置canvas尺寸为视频原始尺寸
            canvas.width = targetVideo.videoWidth || targetVideo.clientWidth;
            canvas.height = targetVideo.videoHeight || targetVideo.clientHeight;
            
            // 检查视频是否已加载
            if (targetVideo.readyState < 2) {
                alert('视频尚未加载完成,请稍后再试!');
                return;
            }

            // 将视频当前帧绘制到canvas
            ctx.drawImage(targetVideo, 0, 0, canvas.width, canvas.height);
            
            // 转换为PNG格式的blob
            canvas.toBlob(function(blob) {
                if (!blob) {
                    alert('截图失败,可能是由于CORS限制!');
                    return;
                }
                
                // 创建下载链接
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                
                // 生成文件名(包含时间戳)
                const now = new Date();
                const timestamp = now.getFullYear() + 
                    String(now.getMonth() + 1).padStart(2, '0') + 
                    String(now.getDate()).padStart(2, '0') + '_' +
                    String(now.getHours()).padStart(2, '0') + 
                    String(now.getMinutes()).padStart(2, '0') + 
                    String(now.getSeconds()).padStart(2, '0');
                
                a.download = `video_screenshot_${timestamp}.png`;
                
                // 触发下载
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                
                // 清理URL对象
                URL.revokeObjectURL(url);
                
                // 显示成功消息
                showMessage('截图成功!');
                
            }, 'image/png', 1.0); // 无损PNG格式,质量为1.0
            
        } catch (error) {
            console.error('截图错误:', error);
            alert('截图失败: ' + error.message);
        }
    }

    // 显示提示消息
    function showMessage(text) {
        const messageDiv = document.createElement('div');
        messageDiv.textContent = text;
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            font-size: 14px;
            z-index: 10000;
            transition: opacity 0.3s;
        `;
        
        document.body.appendChild(messageDiv);
        
        // 3秒后自动消失
        setTimeout(() => {
            messageDiv.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(messageDiv);
            }, 300);
        }, 3000);
    }

    // 监听键盘事件
    document.addEventListener('keydown', function(event) {
        // 检查是否按下Alt+1
        if (event.altKey && event.code === 'Digit1') {
            event.preventDefault();
            captureVideoFrame();
        }
    });

    // 页面加载完成后显示提示
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                if (document.querySelectorAll('video').length > 0) {
                    showMessage('H5视频截图工具已加载,按Alt+1进行截图');
                }
            }, 2000);
        });
    } else {
        setTimeout(() => {
            if (document.querySelectorAll('video').length > 0) {
                showMessage('H5视频截图工具已加载,按Alt+1进行截图');
            }
        }, 2000);
    }

    // 添加右键菜单选项(可选)
    document.addEventListener('contextmenu', function(event) {
        if (event.target.tagName === 'VIDEO') {
            event.preventDefault();
            
            // 创建自定义右键菜单
            const menu = document.createElement('div');
            menu.innerHTML = `
                <div style="background: white; border: 1px solid #ccc; border-radius: 5px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 5px 0; font-size: 14px;">
                    <div style="padding: 8px 15px; cursor: pointer; hover: background-color: #f0f0f0;" onmouseover="this.style.backgroundColor='#f0f0f0'" onmouseout="this.style.backgroundColor='white'">
                        📸 截取视频截图
                    </div>
                </div>
            `;
            menu.style.cssText = `
                position: fixed;
                left: ${event.pageX}px;
                top: ${event.pageY}px;
                z-index: 10001;
            `;
            
            menu.onclick = function() {
                captureVideoFrame();
                document.body.removeChild(menu);
            };
            
            document.body.appendChild(menu);
            
            // 点击其他地方关闭菜单
            setTimeout(() => {
                document.addEventListener('click', function closeMenu() {
                    if (document.body.contains(menu)) {
                        document.body.removeChild(menu);
                    }
                    document.removeEventListener('click', closeMenu);
                }, 100);
            });
        }
    });

})();