当前位置:首页 > TAG信息列表 > 360浏览器调用摄像头

360浏览器调用摄像头

如何设置浏览器调用摄像头(电脑网页摄像头权限开启方法)

如何通过js调用本地摄像头呢?获取后如何对视频进行截图呢?在这里跟大家做一个简易的demo来实现以上几个功能。

涉及到的知识点navigator.getusermedia可以通过该函数来打开摄像头获得流数据canvas.drawimage可以通过该函数来将视频的某帧画到canvas画布上canvas.todataurl可以通过该函数将canvas画布生成图片url实现的功能点打开摄像头暂停摄像头对视频进行截图html简单布局

以下先通过html我们来实现一个简单的布局,包括样式和按钮。

<!doctypehtml>
<htmllang=\"en\">
<head>
<metacharset=\"utf-8\">
<title>h5canvas调用摄像头进行绘制</title>
<style>
html,body{
width:100%;
height:100%;
padding:0px;
margin:0px;
overflow:hidden;
}
#canvas{
width:500px;
height:300px;
}
#video{
width:500px;
height:300px;
}
.btn{
display:inline-block;
text-align:center;
background-color:#333;
color:#eee;
font-size:14px;
padding:5px15px;
border-radius:5px;
cursor:pointer;
}
</style>
</head>
<body>
<videoid=\"video\"autoplay=\"true\"style=\"background-color:#ccc;display:none;\"></video>
<divstyle=\"width:500px;height:300px;margin:30pxauto;\">
<canvasid=\"canvas\"width=\"500px\"height=\"300px\">您的浏览器不支持h5,请更换或升级!</canvas>
<spanclass=\"btn\"filter=\"screenshot\">截图</span>
<spanclass=\"btn\"filter=\"close\">暂停</span>
<spanclass=\"btn\"filter=\"open\">打开</span>
</div>
<divstyle=\"width:500px;height:300px;margin:40pxauto;\"id=\"show\"></div>
</body>
</html>

样子差不多是这样的:

如何设置浏览器调用摄像头(电脑网页摄像头权限开启方法)

hahiahia空白一片

我们将video进行了隐藏,然后加上了几个按钮,还有canvas以及最底部的图片展示区域(用来存放截图图片)。

js实现功能

这里先贴下核心代码:

navigator.getusermedia({
video:{width:500,height:300}
},function(stream){
lv.video.srcobject=stream;
lv.video.onloadedmetadata=function(e){
lv.video.play();
};
},function(err){
alert(err);//弹窗报错
})

相关的知识点可以参考
:https://developer.mozilla.org/en-us/docs/web/api/mediadevices/getusermedia

然后根据页面逻辑实现事件以及其他功能,包括:截图、暂停。

navigator.getusermedia=navigator.getusermedia||navigator.webkitgetusermedia||navigator.mozgetusermedia;
varevents={
open:function(){
lv.open();
},
close:function(){
console.log(lv.timer);
clearinterval(lv.timer);
},
screenshot:function(){
//获得当前帧的图像并拿到数据
varimage=canvas.todataurl(\'jpeg\');
document.getelementbyid(\'show\').innerhtml=\'<imgsrc=\"\'+image+\'\"style=\"width:500px;height:300px;\"/>\'
}
};
varlv={
video:document.getelementbyid(\'video\'),
canvas:document.getelementbyid(\'canvas\'),
timer:null,
media:null,
open:function(){
if(!lv.timer){
navigator.getusermedia({
video:{width:500,height:300}
},function(stream){
lv.video.srcobject=stream;
lv.video.onloadedmetadata=function(e){
lv.video.play();
};
},function(err){
alert(err);//弹窗报错
})
}
if(lv.timer){
clearinterval(lv.timer);
}
//将画面绘制到canvas中
lv.timer=setinterval(function(){
lv.ctx.drawimage(lv.video,0,0,500,300);
},15);
},
init:function(){
lv.ctx=lv.canvas.getcontext(\'2d\');
//绑定事件
document.queryselectorall(\'[filter]\').foreach(function(item){
item.onclick=function(ev){
vartype=this.getattribute(\'filter\');
events[type].call(this,ev);
}
});
returnlv;
}
};
lv.init();

原谅我放荡不羁的命名…


智能马桶之家 爱来客

  • 关注微信关注微信

猜你喜欢

微信公众号