通过HTML5 Video和Canvas实现拍照的功能,功能很简单;另外,因为用到了getUserMedia()函数,目前只能在Chrome和Opera里使用,详见:Can I use getUserMedia/Stream API?
演示地址:HTML5 Webcam Photoing
基本原理:<video>元素用来从WebRTC(亦即你的摄像头)获取图像,然后通过<canvas>来抓取视频;
02 | var streaming = false , |
03 | video = document.querySelector( '#video' ), |
04 | canvas = document.querySelector( '#canvas' ), |
05 | startbutton = document.querySelector( '#startbutton' ), |
09 | navigator.getMedia = ( navigator.getUserMedia || |
10 | navigator.webkitGetUserMedia || |
11 | navigator.mozGetUserMedia || |
12 | navigator.msGetUserMedia); |
15 | { video: true , audio: false }, |
17 | if (navigator.mozGetUserMedia) { |
18 | video.mozSrcObject = stream; |
20 | var vendorURL = window.URL || window.webkitURL; |
21 | video.src = vendorURL.createObjectURL(stream); |
26 | console.log( "An error occured! " + err); |
30 | video.addEventListener( 'canplay' , function (ev){ |
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); |
41 | function takepicture() { |
43 | canvas.height = height; |
44 | canvas.getContext( '2d' ).drawImage(video, 0, 0, width, height); |
47 | startbutton.addEventListener( 'click' , function (ev){ |
个人觉得该功能还是很强大的,以前都是要通过插件来完成,现在可以直接通过HTML来实现了,并且,后期功能方面也可以逐渐加强!
参考资料:
Capture Audio & Video in HTML5
Media Capture and Streams