Javascript Electron как делать скриншоты с видео источника - PullRequest
1 голос
/ 08 мая 2019

Я использую Electron Desktop Capturer https://github.com/electron/electron/blob/master/docs/api/desktop-capturer.md, чтобы делать снимки этого потока через равные промежутки времени. Я использую этот код, но по какой-то причине я получаю сообщение об ошибке:

function takeScr(stream) {
  const video = localStream.getVideoTracks()[0];
  console.log(video)
  const canvas = document.createElement('canvas');
  canvas.getContext("2d").drawImage(video, 0, 0, 300, 300, 0, 0, 300, 300);
}

В данный момент я просто нажимаю кнопку, чтобы активировать эту функцию снимка экрана после начала воспроизведения потока. Журнал консоли показывает видеотрек без проблем с выводом:

MediaStreamTrack {kind: "video", id: "7a19a94f-6077-4e3d-b534-03d138b3f300", label: "Screen", enabled: true, muted: false, …}

но функция canvas.getContext выдает ошибку:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

Здесь есть много вопросов об этой ошибке, но ни один из них не решает мою проблему, и ни один не касается видеопотоков. Некоторые решения заключались в том, что изображение не загружалось при попытке рисования на холст, но, поскольку я нажимаю кнопку через несколько секунд после запуска потока, я уверен, что оно должно быть загружено?

Может быть, я делаю это неправильно, и есть лучший способ сделать скриншоты источника видео из Desktop Capturer?

1 Ответ

3 голосов
/ 08 мая 2019

Я нашел пример в следующем вопросе относительно снятия снимков с видео.

Вы можете сделать что-то вроде этого:

document.getElementById("snap").addEventListener("click", function() {
  snap();
});

// Get handles on the video and canvas elements
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
// Get a handle on the 2d context of the canvas element
var context = canvas.getContext('2d');
// Define some vars required later
var w, h, ratio;

// Add a listener to wait for the 'loadedmetadata' state so the video's dimensions can be read
video.addEventListener('loadedmetadata', function() {
  // Calculate the ratio of the video's width to height
  ratio = video.videoWidth / video.videoHeight;
  // Define the required width as 100 pixels smaller than the actual video's width
  w = video.videoWidth - 100;
  // Calculate the height based on the video's width and the ratio
  h = parseInt(w / ratio, 10);
  // Set the canvas width and height to the values just calculated
  canvas.width = w;
  canvas.height = h;
}, false);

// Takes a snapshot of the video
function snap() {
  // Define the size of the rectangle that will be filled (basically the entire element)
  context.fillRect(0, 0, w, h);
  // Grab the image from the video
  context.drawImage(video, 0, 0, w, h);
}
<video width="400" controls>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<canvas width="364" height="204"></canvas>

<button id="snap">Take screenshot</button>

JSFiddle

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...