Chrome extension screenshot partial image cropping for Retina Display

扶醉桌前 提交于 2021-02-19 02:53:48

问题


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:

On a Macbook with Retina display:

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?


回答1:


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




回答2:


How about this, it works for me.

let ratio = window.devicePixelRatio;
context.drawImage(image,
    dimensions.left*ratio, dimensions.top*ratio,
    dimensions.width*ratio, dimensions.height*ratio,
    0, 0,
    dimensions.width, dimensions.height
);

CanvasAPI: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage



来源:https://stackoverflow.com/questions/32013884/chrome-extension-screenshot-partial-image-cropping-for-retina-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!