Bilibili 一键截图

按 S 键一键截图,并保存成 PNG 格式

当前为 2020-11-10 提交的版本,查看 最新版本

// ==UserScript==
// @name         Bilibili 一键截图
// @description  按 S 键一键截图,并保存成 PNG 格式
// @version      0.1.2
// @author       Kazurin
// @match        https://www.bilibili.com/video/*
// @match        https://www.bilibili.com/bangumi/play/*
// @grant        none
// @namespace https://greasyfork.org/users/699115
// ==/UserScript==

'use strict';
let video, videoTitle, bgmTitle, canvas, ctx, link;

function lazyInitialize() {
    if(!canvas) {
        video = document.querySelector('.bilibili-player-video video');
        videoTitle = document.querySelector('.bilibili-player-video-top-title');
        bgmTitle = document.querySelector('.media-title');
        canvas = document.createElement('canvas');
        ctx = canvas.getContext('2d');
        link = document.createElement('a');
        link.style.display = 'none';
        document.body.appendChild(link);
    }
}

function getVideoCurrentTime(video) {
    let time = Math.round(video.currentTime);
    let seconds = time % 60;
    let minutes = (time - seconds) / 60;
    return minutes + '-' + (seconds < 10 ? '0' : '') + seconds;
}

function downloadScreenshot() {
    lazyInitialize();
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    let dataUrl = canvas.toDataURL('image/png');
    link.href = dataUrl;
    if(window.location.href.indexOf('/bangumi/') >= 0) {
        let bgmEpisode = document.querySelector('#eplist_module .ep-item.cursor .ep-title') ||
            document.querySelector('.ep-section-module .ep-item.cursor .ep-title');
        if(bgmEpisode) {
            link.download = bgmTitle.textContent + ' ' + bgmEpisode.textContent + ' ' + getVideoCurrentTime(video) + '.png';
        } else {
            link.download = bgmTitle.textContent + ' ' + getVideoCurrentTime(video) + '.png';
        }
    } else {
        link.download = videoTitle.textContent + ' ' + getVideoCurrentTime(video) + '.png';
    }
    link.click();
}

document.addEventListener('keydown', e => {
    if(e.keyCode == 83) {
        e.preventDefault = true;
        try {
            downloadScreenshot();
        } catch(e) {
            console.error('截图失败');
            console.error(e);
            window.alert('截图失败,请重试。如果此问题反复出现,请在 F12 控制台查看错误消息,并向开发者反馈。');
        }
    }
});