使用js调用摄像头拍照

使用js调用摄像头拍照

在一些浏览器里已经可以使用web api调用摄像头功能了。
基于此可以经行拍照摄像功能,网上找了些资料,然后实现了简单的拍照功能
演示地址 bingxl.cn/webrtc.html

代码

<!DOCTYPE html>
<html lang="ZH-CN">
<head>
  <meta charset="utf-8">
  <title>web RTC 测试</title>
  <style>
    .booth {
      width:400px;
  <span class="hljs-attribute">background</span>:<span class="hljs-number">#ccc</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">10px</span> solid <span class="hljs-number">#ddd</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
}

</style>
</head>
<body>
<div class=“booth”>
<video id=“video” width=“400” height=“300”></video>
<button id=‘tack’> snap shot</button>
<canvas id=‘canvas’ width=‘400’ height=‘300’></canvas>
<img id=‘img’ src=’’>
</div>

<script>
var video = document.getElementById(‘video’),
canvas = document.getElementById(‘canvas’),
snap = document.getElementById(‘tack’),
img = document.getElementById(‘img’),
vendorUrl = window.URL || window.webkitURL;

<span class="hljs-comment">//媒体对象</span>
navigator.getMedia = navigator.getUserMedia ||
                     navagator.webkitGetUserMedia ||
                     navigator.mozGetUserMedia ||
                     navigator.msGetUserMedia;
navigator.getMedia({
    <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">//使用摄像头对象</span>
    audio: <span class="hljs-literal">false</span>  <span class="hljs-comment">//不适用音频</span>
}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">strem</span>)</span>{
    <span class="hljs-built_in">console</span>.log(strem);
    video.src = vendorUrl.createObjectURL(strem);
    video.play();
}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
    <span class="hljs-comment">//error.code</span>
    <span class="hljs-built_in">console</span>.log(error);
});
snap.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-comment">//绘制canvas图形</span>
    canvas.getContext(<span class="hljs-string">'2d'</span>).drawImage(video, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">400</span>, <span class="hljs-number">300</span>);
    
    <span class="hljs-comment">//把canvas图像转为img图片</span>
    img.src = canvas.toDataURL(<span class="hljs-string">"image/png"</span>);
    
})

</script>
</body>
</html>

demo演示;

特别说明

  1. 有些浏览器可能不支持此功能
  2. 必须通过服务器打开页面,通过files://打开无效
  3. 如果通过远程服务器打开则必须是https协议, http协议也无法使用
此博客出自稻草人LXB,转载请注明原文地址
博客地址:http://www.cnblogs.com/scarecrowlxb/

猜你喜欢

转载自blog.csdn.net/heqiang000/article/details/85278985
今日推荐