HTML5 Video/Canvas拍照初级

通过HTML5 Video和Canvas实现拍照的功能,功能很简单;另外,因为用到了getUserMedia()函数,目前只能在Chrome和Opera里使用,详见:Can I use getUserMedia/Stream API?

演示地址:HTML5 Webcam Photoing

基本原理:<video>元素用来从WebRTC(亦即你的摄像头)获取图像,然后通过<canvas>来抓取视频;

(function() {
 var streaming = false,
 video        = document.querySelector('#video'),
 canvas       = document.querySelector('#canvas'),
 startbutton  = document.querySelector('#startbutton'),
 width = 400,
 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() {
 canvas.width = width;
 canvas.height = height;
 canvas.getContext('2d').drawImage(video, 0, 0, width, height);
 }
 
 startbutton.addEventListener('click', function(ev){
 takepicture();
 ev.preventDefault();
 }, false);
 })();

个人觉得该功能还是很强大的,以前都是要通过插件来完成,现在可以直接通过HTML来实现了,并且,后期功能方面也可以逐渐加强!

参考资料:

Capture Audio & Video in HTML5

Media Capture and Streams

你可能感兴趣的:(canvas,html5,video,webcam)