1
votes

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.
For now,I have been using this API of chrome

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.
How can I achieve the same?
Thanks a lot !

1

1 Answers

3
votes

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
  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.

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