html5

来源:互联网 发布:c语言课程设计案例 编辑:程序博客网 时间:2024/06/06 03:04

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

演示地址:HTML5 Webcam Photoing

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

view source
print?
01(function() {
02 varstreaming = 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 varvendorURL = 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 functiontakepicture() {
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

原创粉丝点击