简体   繁体   English

如何在chrome扩展程序中使用javascript拍摄某些特定区域的屏幕截图?

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

I am working on a chrome extension in which I want to take screenshot of only specific portion of the current window, not the entire window itself. 我正在开发一个chrome扩展程序,该程序中我只想截取当前窗口的特定部分而不是整个窗口本身的屏幕快照。
For now,I have been using this API of chrome 目前,我一直在使用chrome这个API

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

It takes the screenshot of entire page but I want screenshot of my given x,y coordinates. 它需要整个页面的屏幕截图,但是我想要给定的x,y坐标的屏幕截图。
How can I achieve the same? 我怎样才能达到同样的目的?
Thanks a lot ! 非常感谢 !

One possible approach would be: 一种可能的方法是:

  1. Use CanvasRenderingContext2D.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) to draw the screenshot onto the canvas, in the meanwhile making use of corresponding parameters to crop the image 使用CanvasRenderingContext2D.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)将屏幕快照绘制到画布上,同时利用相应的参数来裁剪图像
  2. Use HTMLCanvasElement.toDataURL to convert canvas to data URI containing a representation of the image, or CanvasRenderingContext2D.getImageData() to return an ImageData object, it depends on your needs. 使用HTMLCanvasElement.toDataURL将画布转换为包含图像表示形式的数据URI ,或者使用CanvasRenderingContext2D.getImageData()返回ImageData对象,这取决于您的需要。

Sample code ( Please be aware depending on your needs, you may want to move inner logic to content scripts ): 示例代码( 请注意,根据您的需要,您可能希望将内部逻辑移至内容脚本 ):

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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM