javascript 在Chrome中拍摄完整屏幕截图

polhcujo  于 2023-02-28  发布在  Java
关注(0)|答案(2)|浏览(122)

我开发了一个小的chrome扩展,它可以从当前页面截图。问题是,当当前区域的一部分被覆盖时,例如检查器或不在视图中,截图会被裁剪。有没有办法得到全屏?以下是我的代码(精简):

function createScreenshot() {
  chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
    chrome.tabs.captureVisibleTab({ format: "png" }, function (screenshotUrl) {
        cropImage(screenshotUrl, "Screenshot");
      });
  });
}

function cropImage(url, fileName) {
  var img = new Image();
  img.onload = function () {
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");
    
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    
    chrome.storage.sync.get(null, function(data) {
      downloadImage(canvas, fileName + ".png");
    });
  };
  img.src = url;
}

比如说这是我想用4k分辨率拍摄的页面:

正如你所看到的,它不适合实际的屏幕分辨率,但结果只是有效区域(甚至更小):

有没有办法得到“不可见”的部分?
雷格拉兹马丁

wooyq4lh

wooyq4lh1#

您的代码中有细微的更正
必须在drawImage中传递画布宽度和高度

ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

您需要获取base64字符串

let image = canvas.toDataURL("image/png");

最后,你会得到你想要的结果
希望此解决方案对您有所帮助

bxjv4tth

bxjv4tth2#

此处建议in reddit

chrome.tabs.captureVisibleTab(null, {format: "png"}, function(dataUrl) {
  var img = new Image();
  img.src = dataUrl;
  img.onload = function() {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = document.body.scrollHeight;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    chrome.tabs.executeScript(null, {code: "window.scrollTo(0, document.body.scrollHeight)"}, function() {
      setTimeout(function() {
        chrome.tabs.captureVisibleTab(null, {format: "png"}, function(dataUrl) {
          var img2 = new Image();
          img2.src = dataUrl;
          img2.onload = function() {
            ctx.drawImage(img2, 0, img.height, img2.width, img2.height);
            var finalDataUrl = canvas.toDataURL("image/png");
            // Use finalDataUrl as needed
          }
        });
      }, 500);
    });
  }
});

相关问题