html5

通過HTML5 Video和Canvas實現拍照的功能,功能很簡單;另外,因爲用到了getUserMedia()函數,目前只能在Chrome和Opera裏使用,詳見:Can I use getUserMedia/Stream API?

演示地址:HTML5 Webcam Photoing

基本原理:<video>元素用來從WebRTC(亦即你的攝像頭)獲取圖像,然後通過<canvas>來抓取視頻;

01 (function() {
02  var streaming = false,
03  video        = document.querySelector('#video'),
04  canvas       = document.querySelector('#canvas'),
05  startbutton  = document.querySelector('#startbutton'),
06  width = 400,
07  height = 0;
08    
09  navigator.getMedia = ( navigator.getUserMedia ||
10                          navigator.webkitGetUserMedia ||
11                          navigator.mozGetUserMedia ||
12                          navigator.msGetUserMedia);
13    
14  navigator.getMedia(
15  { video: true, audio: false },
16  function(stream) {
17   if (navigator.mozGetUserMedia) {
18  video.mozSrcObject = stream;
19   } else {
20  var vendorURL = window.URL || window.webkitURL;
21  video.src = vendorURL.createObjectURL(stream);
22   }
23   video.play();
24  },
25  function(err) {
26   console.log("An error occured! " + err);
27  }
28  );
29    
30  video.addEventListener('canplay', function(ev){
31  if (!streaming) {
32   height = video.videoHeight / (video.videoWidth/width);
33   video.setAttribute('width', width);
34   video.setAttribute('height', height);
35   canvas.setAttribute('width', width);
36   canvas.setAttribute('height', height);
37   streaming = true;
38  }
39  }, false);
40    
41  function takepicture() {
42  canvas.width = width;
43  canvas.height = height;
44  canvas.getContext('2d').drawImage(video, 0, 0, width, height);
45  }
46    
47  startbutton.addEventListener('click', function(ev){
48  takepicture();
49  ev.preventDefault();
50  }, false);
51  })();

個人覺得該功能還是很強大的,以前都是要通過插件來完成,現在可以直接通過HTML來實現了,並且,後期功能方面也可以逐漸加強!

參考資料:

Capture Audio & Video in HTML5

Media Capture and Streams

發佈了24 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章