Trying to capture desktop image using getUserMedia and canvas

只愿长相守 提交于 2019-12-04 12:22:28

You have to wait for the video actually loads the stream : rewrite your gotStream like so :

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();
  }

Also, in order to get a better quality image, you have to set the mandatory maxHeight and maxWidth of the getUserMedia() call :

navigator.webkitGetUserMedia({
      audio:false,
      video: { mandatory: { chromeMediaSource: "desktop",
                            chromeMediaSourceId: id,
                            maxWidth: 4000,
                            maxHeight: 4000} }
  }, gotStream, getUserMediaError);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!