Skip to content

Instantly share code, notes, and snippets.

@tzmartin
Created September 18, 2016 01:44
Show Gist options
  • Save tzmartin/ec6b619684d58628375083753899b5cb to your computer and use it in GitHub Desktop.
Save tzmartin/ec6b619684d58628375083753899b5cb to your computer and use it in GitHub Desktop.
DOM element screen capture

"Fakes" an element capture by cropping a full screen image to the boundaries of a DOM element

var canvas = null;
function capture(tabId, dimensions) {
    chrome.tabs.get(tabId, function(tab) {
        chrome.tabs.captureVisibleTab(tab.windowId, { format: "png" }, function(dataUrl) {
            if (!canvas) {
                canvas = document.createElement("canvas");
                document.body.appendChild(canvas);
            }
            var image = new Image();
            image.onload = function() {
                canvas.width = dimensions.width;
                canvas.height = dimensions.height;
                var context = canvas.getContext("2d");
                context.drawImage(image,
                    dimensions.left, dimensions.top,
                    dimensions.width, dimensions.height,
                    0, 0,
                    dimensions.width, dimensions.height
                );
                var croppedDataUrl = canvas.toDataURL("image/png");
                chrome.tabs.create({
                    url: croppedDataUrl,
                    windowId: tab.windowId
                });
            }
            image.src = dataUrl;
        });
    });
}

Source: https://github.com/tlrobinson/element-capture/blob/master/background.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment