html5调用摄像头并拍照

随着flash被禁用,flash上传附件的方式已成为过去,现在开始用html5上传了.本片文章就是介绍如何使用html5拍照,其实挺简单的原理:

调用摄像头采集视频流,利用canvas的特性生成base64图片,

其完整代码如下,需要使用https访问才不会有调用摄像头安全问题,另外IE内核是无法使用的.这个可以作为一个单独页面来被父页面调用

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>html5拍照</title>
<style type="text/css">
body{overflow-y:auto;overflow-x:auto;margin:0;}
#cameraBtn,#cameraDiv{padding:5px;}
.big-btn-blue{ display:inline-block; min-width:80px; height:30px; margin:0 5px; padding:0 15px; vertical-align:top; line-height:30px; text-align:center; font-size:14px; font-family: "微软雅黑";
 color:#fff; border-radius:2px; box-sizing:border-box; -moz-box-sizing:border-box; -webkit-box-sizing:border-box; cursor:pointer; }
.big-btn-blue{ -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; transition: all 0.3s ease;}/*动画*/
.big-btn-blue{ border:1px solid #3194dd; background-color:#3194dd;}/*纯蓝色*/
</style>
<script type="text/javascript">
//访问用户媒体设备的兼容方法
function getUserMedia(constrains,success,error){
    if(navigator.mediaDevices.getUserMedia){
        //最新标准API
        navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
    } else if (navigator.webkitGetUserMedia){
        //webkit内核浏览器
        navigator.webkitGetUserMedia(constrains).then(success).catch(error);
    } else if (navigator.mozGetUserMedia){
        //Firefox浏览器
        navagator.mozGetUserMedia(constrains).then(success).catch(error);
    } else if (navigator.getUserMedia){
        //旧版API
        navigator.getUserMedia(constrains).then(success).catch(error);
    }else{
        alert("不支持的浏览器");
    }
}
//成功的回调函数
function success(stream){
    //兼容webkit内核浏览器
    var CompatibleURL = window.URL || window.webkitURL;
    //将视频流设置为video元素的源
    try {
        video.srcObject = stream;
    } catch (e) {
        video.src = CompatibleURL.createObjectURL(stream);
    }
    //播放视频
    video.play();
}
//异常的回调函数
function error(error){
   alert("访问用户媒体设备失败,"+error.name+""+error.message);
}

/**
 * 获取当前静态页面的参数
 * 返回值和使用方法类似java request的getparamater
 * 不同: 当取得的为数组(length>1)时调用toString()返回(逗号分隔每个元素)
 * @param {Object} name
 * @return {TypeName} 
 */
function getPara(name,search){
    var p = getParas(name,search);
    if(p.length==0){
        return null;
    }else if(p.length==1){
        return p[0];
    }else{
        return p.toString();
    }
}

/**获取当前静态页面的参数
 * 返回值和使用方法类似java request的getparamaterValues
 * @param {Object} name 要取出的参数名,可以在参数字符串中重复出现
 * @param {Object} search 手工指定要解析的参数字符串,默认为当前页面后跟的参数
 * @return {TypeName} 
 */
function getParas(name,search){
    if(!search){
        search = window.location.search.substr(1);//1.html?a=1&b=2
    }
    var para = [];
    var pairs = search.split("&");//a=1&b=2&b=2&c=2&b=2
    for(var i=0;i<pairs.length;i=i+1){
        var sign = pairs[i].indexOf("="); 
        if(sign == -1){//如果没有找到=号,那么就跳过,跳到下一个字符串(下一个循环)。    
            continue; 
        }
        var aKey = pairs[i].substring(0,sign);
        if(aKey==name){
            para.push(unescape(pairs[i].substring(sign+1)));
        }
    }
    return para;
}
//开启摄像头
function captureInit(){
    if ((navigator.mediaDevices!=undefined && navigator.mediaDevices.getUserMedia!=undefined) 
            || navigator.getUserMedia!=undefined
            || navigator.webkitGetUserMedia!=undefined
            || navigator.mozGetUserMedia!=undefined){
        document.getElementById("help").style.display="none";
        //调用用户媒体设备,访问摄像头,改为触发事件
        getUserMedia({video:{width:imgWidth,height:imgHeight}},success,error);
        if(captureState==0){
            captureState=1;//标记此按钮已点击
        }
    } else {
        captureState=0;//异常标识按钮没点
        alert("你的浏览器不支持访问用户媒体设备或访问地址不是https开头,您可以点击右侧下载解决方案");
        document.getElementById("help").style.display="inline-block";
    }
}
//注册拍照按钮的单击事件
function capture(){
    //绘制画面
    if(captureState==0){
        alert("请先开启摄像头");
        return;
    }
    context.drawImage(video,0,0,imgWidth,imgHeight);//后面两个长宽
    //canvas.toDataURL("image/png");//即可得到base64编码
    captureState=2;
}
//确认按钮返回给父页面的函数
function queren(){
    if(captureState!=2){
        alert("请先开启摄像头并拍照");
        return;
    }
    var base64=canvas.toDataURL("image/jpeg");
    var pics={};
    pics.filetypeid=filetypeid;//返回给前端
    pics.base64=base64;
    if(window.opener){
        window.opener[cb](pics);// /FileUploadTmp/为项目临时文件夹相对路径
        window.close();
    }else if(window.parent){
        window.parent[cb](pics);
        window.parent.$("#dialog_ifr_html").dialog("close");//close会导致flash未执行完就销毁,页面JS报错
    }else{
        window.close();
    }
}
</script>
</head>

<body>
<div id="cameraBtn">
    <input type="button" id="init" onclick="captureInit()" value="开启摄像头"/>
    <input type="button" id="capture" onclick="capture()" value="拍照"/>
    <input type="button" id="queren" onclick="queren()" value="确定"/>
    <span id="help" style="display:none;"><a href="/static/ad/down/camera.doc">点此下载无法拍照的解决方案</a></span>
</div>
<div id="cameraDiv">
    <!-- 视频流 -->
      <video id="video" autoplay style="width: 300px;height: 200px"></video>
     <!--描绘video截图-->
    <canvas id="canvas" width="300" height="200"></canvas>
</div>
<script type="text/javascript">
var cb=getPara("cb")||"setImg";
var filetypeid=getPara("filetypeid")||"filetypeid";//附件类型id
var video=document.getElementById("video");
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var imgWidth=getPara("width")||"300";//这个值div的宽一致
var imgHeight=getPara("height")||"200";//这个值div的高一致
var captureState=0;//未开启,1已开启,2已拍照,为2才可点击确认按钮
var style = getPara("style")||"big-btn-blue";
video.style.width=imgWidth;
video.style.height=imgHeight;
var st = style.split(",");
document.getElementById("init").className=st[0];
document.getElementById("capture").className=st[1]||st[0];
document.getElementById("queren").className=st[2]||st[0];
document.getElementById("help").className=st[3]||st[0];
</script>
</body>
</html>

相信略懂js和html5的人都能看懂代码,非常的简单.而且都不需要用到jquery.

另外备注下:IE内核浏览器是无法实现的.因为不支持getUserMedia方法.

注:文章内容来自于本人在CSDN上发布的文章

相关文章

HTML5和CSS3实现3D展示商品信息的代码
利用HTML5中的Canvas绘制笑脸的代码
Html5剪切板功能的实现
如何通过HTML5触摸事件实现移动端简易进度条
Html5移动端获奖无缝滚动动画实现
关于HTML5和CSS3实现机器猫的代码