如何从Html中的网络摄像头拍摄图像

时间:2017-01-10 17:44:29

标签: javascript camera

我只想知道如何使用javascript从网络摄像头拍摄图像并将该图像创建到网页上。我已经看到了其他方法,但没有一个解释如何使用它。有人可以解释如何做到这一点吗?

1 个答案:

答案 0 :(得分:3)

最初,canvas元素的显示设置为none。只有视频帧可见。当用户点击CAPTURE时,将显示画布并显示视频元素。按钮内容更改为RETAKE。

在codepen capture image using javascript

的工作演示

(function() {

  var streaming = false,
    video = document.querySelector('#video'),
    canvas = document.querySelector('#canvas'),
    buttoncontent = document.querySelector('#buttoncontent'),
    photo = document.querySelector('#photo'),
    startbutton = document.querySelector('#startbutton'),
    width = 320,
    height = 0;

  navigator.getMedia = (navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia);

  navigator.getMedia({
      video: true,
      audio: false
    },
    function(stream) {
      if (navigator.mozGetUserMedia) {
        video.mozSrcObject = stream;
      } else {
        var vendorURL = window.URL || window.webkitURL;
        video.src = vendorURL.createObjectURL(stream);
      }
      video.play();
    },
    function(err) {
      console.log("An error occured! " + err);
    }
  );

  video.addEventListener('canplay', function(ev) {
    if (!streaming) {
      height = video.videoHeight / (video.videoWidth / width);
      video.setAttribute('width', width);
      video.setAttribute('height', height);
      canvas.setAttribute('width', width);
      canvas.setAttribute('height', height);
      streaming = true;
    }
  }, false);

  function takepicture() {
  	video.style.display = "none";
    canvas.style.display = "block";
    startbutton.innerText= "RETAKE";
  	canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(video, 0, 0, width, height);
    var data = canvas.toDataURL('image/png');
    photo.setAttribute('src', data);
  }

  startbutton.addEventListener('click', function(ev) {
  	if(startbutton.innerText==="CAPTURE")
    {
    	takepicture();
    }
    else
    {
    	video.style.display = "block";
    	canvas.style.display = "none";
      startbutton.innerText= "CAPTURE";
    }
    ev.preventDefault();
  }, false);

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="video"></video>
<canvas id="canvas" style="display:none;"></canvas>
<div id="buttoncontent">

</div>
<button id="startbutton">CAPTURE</button>