2013-08-19 67 views
5

我知道這裏有captureVisibleTab,但是如何剪切製表符的結果截圖,以便只剩下一個HTML元素?如何在Chrome擴展中捕獲單個HTML元素的屏幕截圖?

+2

使用內容腳本獲取元素的相對位置和尺寸,使用此信息在畫布上繪製屏幕截圖,然後從畫布中讀取最終(裁剪後)的圖像。 –

+0

@RobW,謝謝,我沒有考慮使用畫布。我會接受你的評論作爲答案,如果這是可能的! :) – spektom

+0

編寫我的評論的實施,發佈它作爲答案並接受它。編寫正確的實現可能需要5-20分鐘(請記住,captureVisibleTab只捕獲標籤的可見部分,而不是整個頁面,因此您可能需要滾動到正確的位置)。 –

回答

4

爲此,您需要onMessage,sendMessagecaptureVisibleTabonMessagechrome.runtime,sendMessagecaptureVisibleTab的方法都是tabs的方法。

清單

在manifest文件中,您必須對tabs,並且<all_urls>權限添加到您的manifest文件。沒有權限,這將無法正常工作。

"permissions": [ 
    "tabs", 
    "<all_urls>" 
], 

內容腳本

在你的內容的腳本文件,你需要添加以下。這使您可以與您的背景頁面進行交流,以獲取活動選項卡的屏幕截圖。

chrome.runtime.sendMessage({ chromeAction: "screenshot" }, function (imageString) { 
    console.log(imageString); 
}); 

背景腳本/頁

這裏就是奇蹟發生。

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { 
    if (request.chromeAction === "screenshot") { 
     createScreenshot(function (dataURL) { 
      createImage(dataURL); 
     }); 
     return true; 
    } 
}); 

// here we create a new image 
function createImage(dataURL) { 
    // create a canvas 
    var canvas = createCanvas(500, 500); 
    // get the context of your canvas 
    var context = canvas.getContext('2d'); 
    // create a new image object 
    var croppedImage = new Image(); 

    croppedImage.onload = function() { 
     // this is where you manipulate the screenshot (cropping) 
     // parameter 1: source image (screenshot) 
     // parameter 2: source image x coordinate 
     // parameter 3: source image y coordinate 
     // parameter 4: source image width 
     // parameter 5: source image height 
     // parameter 6: destination x coordinate 
     // parameter 7: destination y coordinate 
     // parameter 8: destination width 
     // parameter 9: destination height 
     context.drawImage(croppedImage, 10, 10, 300, 300, 0, 0, 250, 250); 

     // canvas.toDataURL() contains your cropped image 
     console.log(canvas.toDataURL()); 
    }; 
    croppedImage.src = dataURL; // screenshot (full image) 
} 

// creates a canvas element 
function createCanvas(canvasWidth, canvasHeight) { 
    var canvas = document.createElement("canvas"); 

    // size of canvas in pixels 
    canvas.width = canvasWidth; 
    canvas.height = canvasHeight; 
    return canvas; 
} 

// calling the captureVisibleTab method takes a screenhot 
function createScreenshot(callback) { 
    // you can have two image formats (jpeg and png) 
    // for jpeg use { format: "jpeg", quality: 100 } (you can adjust the jpeg image quality from 0-100) 
    // for png use { format: "png" } 
    chrome.tabs.captureVisibleTab(null, { format: "png" }, callback); 
} 

裁剪

爲了更好地理解drawImage帆布方法的閱讀完整documentation

+0

@BrunoLM下面是一些讓你開始的代碼。 – Daniel

相關問題