- <video id="video">
- </video>
获取摄像头影像主要是通过
这个接口,这个接口的支持情况已经逐渐变好了:不过,使用的时候还是要加上前缀的,兼容代码:
- navigator.getUserMedia
- navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
- 语法:navigator.getUserMedia(constraints, successCallback, errorCallback);
参数说明:
:Object 类型,指定了请求使用媒体的类型
- constraints
:启用成功时的函数,它传入一个参数,为视频流对象,可以进一步通过
- succeCallback
接口把视频流转换为对象 URL。
- window.URL.createObjectURL()
:启动失败时的函数。它传入一个参数,为错误对象(chrome)或错误信息字符串(Firefox),可能值:
- errorCallback
PERMISSION_DENIED:用户拒绝提供信息。
NOT_SUPPORTED_ERROR:浏览器不支持硬件设备。
MANDATORY_UNSATISFIED_ERROR:无法发现指定的硬件设备。
例如:要启用视频设备(摄像头),可这样:
- navigator.getUserMedia({
- video: true
- });
如果要同时启用视频设备和音频设备,可这样:
- navigator.getUserMedia({
- video: true,
- audio: true
- });
2、 获取摄像头
3、 截图 除了实时直播外,我们还可以做实时截图效果,这时我们需要利用
- var URL = window.URL || window.webkitURL; // 获取到window.URL对象
- navigator.getUserMedia({
- video: true
- },
- function(stream) {
- video.src = URL.createObjectURL(stream); // 将获取到的视频流对象转换为地址
- video.play();
- },
- function(error) {
- console.log(error.name || error);
- });
元素来画图,代码如下:
- <canvas>
4、 保存图片 当然,截图后,你也可以保存下来:
- <canvas id="canvas">
- </canvas>
- var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d');
- var width = video.width; var height = video.height; canvas.width = width;
- canvas.height = height; ctx.drawImage(video, 0, 0, width, height);
- <a download='snap.png' id="download">
- 下载图片
- </a>
- var url = canvas.toDataURL('image/png'); document.getElementById('download').src
- = url;
5、 完整实例
实例代码(由于安全限制问题,请将代码复制到本地运行):
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>
- </title>
- <style>
- #canvas,#video { float: left; margin-right: 10px; background: #fff; }
- .box { overflow: hidden; margin-bottom: 10px; }
- </style>
- </head>
- <body>
- <div class="box">
- <video id="video" width="400" height="300">
- </video>
- <canvas id="canvas">
- </canvas>
- </div>
- <button id="live">
- 直播
- </button>
- <button id="snap">
- 截图
- </button>
- <script>
- var video = document.getElementById('video');
- var canvas = document.getElementById('canvas');
- var ctx = canvas.getContext('2d');
- var width = video.width;
- var height = video.height;
- canvas.width = width;
- canvas.height = height;
- function liveVideo() {
- var URL = window.URL || window.webkitURL; // 获取到window.URL对象
- navigator.getUserMedia({
- video: true
- },
- function(stream) {
- video.src = URL.createObjectURL(stream); // 将获取到的视频流对象转换为地址
- video.play(); // 播放
- //点击截图
- document.getElementById("snap").addEventListener('click',
- function() {
- ctx.drawImage(video, 0, 0, width, height);
- var url = canvas.toDataURL('image/png');
- document.getElementById('download').href = url;
- });
- },
- function(error) {
- console.log(error.name || error);
- });
- }
- document.getElementById("live").addEventListener('click',
- function() {
- liveVideo();
- });
- </script>
- </body>
- </html>
来源: http://www.cnblogs.com/libin-1/p/6142910.html