Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension screenshot partial image cropping for Retina Display

I made a chrome extension, which captures a single element (div) of a website.

I used chrome.tabs > captureVisibleTab to make a screenshot. Then, with the coordinates (x/y) and sizes (width/height) of the element (div) I crop the screenshot.

This works fine for me on non-retina displays. But not so on a Macbook with Retina display.

For example, on www.247activemedia.com, we want to capture the header div with the logo (id="header").

On non-retina result is:enter image description here

On a Macbook with Retina display:

enter image description here

Cropping failed there, and also the resultion is not correct.

Here is the code:

chrome.tabs.captureVisibleTab(tab.windowId, { format: "png" }, function(screenshot) {
            if (!canvas) {
                canvas = document.createElement("canvas");
                document.body.appendChild(canvas);
            }
            var partialImage = new Image();
            partialImage.onload = function() {
                canvas.width = dimensions.width;
                canvas.height = dimensions.height;
                var context = canvas.getContext("2d");
                context.drawImage(
                    partialImage,
                    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
                });
            }
            partialImage.src = screenshot;

        });

How can I fix this for Retina Displays?

like image 437
Danzzz Avatar asked Nov 09 '22 07:11

Danzzz


1 Answers

Ok, thanks to @gui47 -- the answer is to detect scale with window.devicePixelRatio which is returning 2 on my MBP

like image 92
neaumusic Avatar answered Nov 14 '22 21:11

neaumusic