如何在Chrome扩展中捕获单个HTML元素的屏幕截图?

8
我知道有一个captureVisibleTab,但是如何切割选取某个 HTML 元素后的屏幕截图呢?

2
使用内容脚本获取元素的相对位置和尺寸,利用这些信息在画布上绘制屏幕截图,然后从画布中读取最终(裁剪后)的图像。 - Rob W
@RobW,谢谢,我没有考虑过使用画布。如果可能的话,我会接受您的评论作为答案! :) - Michael Spector
编写我的评论实现,将其作为答案发布并接受。编写正确的实现可能需要5-20分钟(请记住,captureVisibleTab仅捕获选项卡的可见部分,而不是整个页面,因此您可能需要滚动到正确的位置)。 - Rob W
有人可以分享一些代码吗? - BrunoLM
1个回答

6
为此,您需要使用 onMessagesendMessagecaptureVisibleTab。其中,onMessagechrome.runtime 的一个方法,sendMessagecaptureVisibleTab 均是 tabs 的方法。 清单文件 在清单文件中,您必须将 tabs<all_urls> 权限添加到您的清单文件中。没有这些权限,就无法工作。
"permissions": [
    "tabs",
    "<all_urls>"
],

内容脚本

在您的内容脚本文件中,您需要添加以下内容。这将允许您与后台页面通信,以截取活动选项卡的屏幕截图。

chrome.runtime.sendMessage({ chromeAction: "screenshot" }, function (imageString) {
    console.log(imageString);
});

背景脚本/页面

这就是魔法发生的地方。

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.chromeAction === "screenshot") {
        createScreenshot(function (dataURL) {
            createImage(dataURL);
        });
        return true;
    }
});

// here we create a new image
function createImage(dataURL) {
    // create a canvas
    var canvas = createCanvas(500, 500);
    // get the context of your canvas
    var context = canvas.getContext('2d');
    // create a new image object
    var croppedImage = new Image();

    croppedImage.onload = function() {
        // this is where you manipulate the screenshot (cropping)
        // parameter 1: source image (screenshot)
        // parameter 2: source image x coordinate
        // parameter 3: source image y coordinate
        // parameter 4: source image width
        // parameter 5: source image height
        // parameter 6: destination x coordinate
        // parameter 7: destination y coordinate
        // parameter 8: destination width
        // parameter 9: destination height
        context.drawImage(croppedImage, 10, 10, 300, 300, 0, 0, 250, 250);

        // canvas.toDataURL() contains your cropped image
        console.log(canvas.toDataURL());
    };
    croppedImage.src = dataURL; // screenshot (full image)
}

// creates a canvas element
function createCanvas(canvasWidth, canvasHeight) {
    var canvas = document.createElement("canvas");

    // size of canvas in pixels
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    return canvas;
}

// calling the captureVisibleTab method takes a screenhot
function createScreenshot(callback) {
    // you can have two image formats (jpeg and png)
    // for jpeg use { format: "jpeg", quality: 100 } (you can adjust the jpeg image quality from 0-100) 
    // for png use { format: "png" }
    chrome.tabs.captureVisibleTab(null, { format: "png" }, callback);
}

裁剪

为了更好地理解drawImage画布方法,请阅读完整的文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接