gpt4 book ai didi

javascript - 尝试使用 getUserMedia 和 Canvas 捕获桌面图像

转载 作者:可可西里 更新时间:2023-11-01 14:45:15 24 4
gpt4 key购买 nike

我正在制作一个 chrome 扩展程序,通过它我可以获取用户桌面的屏幕截图。我正在使用 chrome.desktopCapture API 来获取所选窗口的流。我正在动态创建视频元素。一旦设置了它的源,我就调用了 play() 方法。然后我创建了一个 Canvas 元素并用它来绘制视频图像。我也可以使用 canvas.toDataURL() 获取 dataURL,但是当我打开这个 url 时,我看不到图像。而且即使在新捕获期间此 URL 值也保持不变。

list .json -

{
"name": "Desktop Capture Example",
"description": "Show desktop media picker UI",
"version": "1",
"manifest_version": 2,
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "Take a screen shot of Desktop!"
},
"permissions": [
"desktopCapture"
]
}

背景.js -

var pending_request_id = null;

chrome.browserAction.onClicked.addListener(function() {

pending_request_id = chrome.desktopCapture.chooseDesktopMedia(["screen", "window"],onAccessApproved);

});

function gotStream(stream) {
console.log("Received local stream");
var video = document.createElement('video');
video.src = URL.createObjectURL(stream);
video.play();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(video, 0, 0, 640, 480);
var url = canvas.toDataURL();
console.log(url);
//localstream = stream;
//stream.onended = function() { console.log("Ended"); };
}

function getUserMediaError() {
console.log("getUserMedia() failed.");
}

function onAccessApproved(id) {
if (!id) {
console.log("Access rejected.");
return;
}
navigator.webkitGetUserMedia({
audio:false,
video: { mandatory: { chromeMediaSource: "desktop",
chromeMediaSourceId: id } }
}, gotStream, getUserMediaError);
}

最佳答案

您必须等待视频实际加载流:像这样重写您的 gotStream:

function gotStream(stream) {
console.log("Received local stream");
var video = document.createElement('video');
video.addEventListener('loadedmetadata',function(){
var canvas = document.createElement('canvas');
canvas.width = this.videoWidth;
canvas.height = this.videoHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var url = canvas.toDataURL();
console.log(url);
// will open the captured image in a new tab
window.open(url);
},false);
video.src = URL.createObjectURL(stream);
video.play();
}

此外,为了获得更好质量的图像,您必须设置 getUserMedia() 调用的强制性 maxHeight 和 maxWidth :

navigator.webkitGetUserMedia({
audio:false,
video: { mandatory: { chromeMediaSource: "desktop",
chromeMediaSourceId: id,
maxWidth: 4000,
maxHeight: 4000} }
}, gotStream, getUserMediaError);

关于javascript - 尝试使用 getUserMedia 和 Canvas 捕获桌面图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31312293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com