2
4

1 回答 1

2

不知道您的代码是什么样的,但我设法通过这段代码获得了流畅的体验:

(您还会在这里找到非常好的示例:https ://mozdevs.github.io/MediaRecorder-examples/ )

<!doctype html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="script.js"></script>
</head>
<body>
  <canvas id="canvas" style="background: black"></canvas>
</body>
// DISCLAIMER: The structure of this code is largely based on examples
// given here: https://mozdevs.github.io/MediaRecorder-examples/.

window.onload = function () {
  navigator.mediaDevices.getDisplayMedia({
    video: true
  })
  .then(function (stream) {

    var video = document.createElement('video');
    // Use "video.srcObject = stream;" instead of "video.src = URL.createObjectURL(stream);" to avoid
    // errors in the examples of https://mozdevs.github.io/MediaRecorder-examples/
    // credits to https://stackoverflow.com/a/53821674/5203275
    video.srcObject = stream;
    video.addEventListener('loadedmetadata', function () {
      initCanvas(video);
    });
    video.play();
  });
};

function initCanvas(video) {

  var canvas = document.getElementById('canvas');

  // Margins around the video inside the canvas.
  var xMargin     = 100;
  var yMargin     = 100;
  
  var videoWidth  = video.videoWidth;
  var videoHeight = video.videoHeight;

  canvas.width  = videoWidth  + 2 * xMargin;
  canvas.height = videoHeight + 2 * yMargin;

  var context = canvas.getContext('2d');
  var draw = function () {
    // requestAnimationFrame(draw) will render the canvas as fast as possible
    // if you want to limit the framerate a particular value take a look at
    // https://stackoverflow.com/questions/19764018/controlling-fps-with-requestanimationframe
    requestAnimationFrame(draw);
    context.drawImage(video, xMargin, yMargin, videoWidth, videoHeight);
  };

  requestAnimationFrame(draw);
}
于 2020-05-03T11:33:45.783 回答