HTML如何长截图谷歌,google-chrome – 如何在Chrome扩展程序中捕获单个HTML元素的屏幕截图?...

为此,您需要

onMessage,

sendMessage和

captureVisibleTab. onMessage是

chrome.runtime的方法,sendMessage和captureVisibleTab都是

tabs的方法.

表现

在清单文件中,您必须添加选项卡,并且< all_urls>对manifest文件的权限.没有权限,这将无法正常工作.

"permissions": [

"tabs",

""

],

内容脚本

在内容脚本文件中,您需要添加以下内容.这允许您与背景页面进行通信,以获取活动选项卡的屏幕截图.

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 canvas方法,请阅读完整的documentation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值