我如何在chrome扩展中使用javascript截取一些特定区域的屏幕截图

How can I take screenshot of some specific area using javascript in chrome extension?

本文关键字:截取 屏幕截图 区域 javascript chrome 扩展      更新时间:2023-09-26

我正在制作一个chrome扩展,我想截取当前窗口的特定部分,而不是整个窗口本身的屏幕截图。
现在,我一直在使用这个API的chrome

chrome.tabs.captureVisibleTab(null,{},function(dataUri){
            // datauri is the screenshot
        });

它截取了整个页面的截图,但我想截取给定的x,y坐标。
我怎样才能达到同样的效果呢?
非常感谢!

一种可能的方法是:

  1. 使用CanvasRenderingContext2D.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)将截图绘制到画布上,同时使用相应的参数裁剪图像
  2. 使用HTMLCanvasElement.toDataURL将画布转换为包含图像表示的数据URI,或者使用CanvasRenderingContext2D.getImageData()返回ImageData对象,这取决于您的需要。

示例代码(请注意,根据您的需要,您可能希望将内部逻辑移动到内容脚本):

chrome.tabs.captureVisibleTab(null, {}, function(dataUri) {
    var img = new Image();
    img.onload = function() {
        var canvas = document.createElement('canvas');
        canvas.width = WIDTH;
        canvas.height = HEIGHT;
        var context = canvas.getContext('2d');
        // Assuming px,py as starting coordinates and hx,hy be the width and the height of the image to be extracted
        context.drawImage(img, px, py, hx, hy, 0, 0, WIDTH, HEIGHT);
        var croppedUri = canvas.toDataURL('image/png');
        // You could deal with croppedUri as cropped image src.
    };
    img.src = dataUri;
});