近来做了一个手机扫码的网页应用, 由于没有其他载体app的帮助 , 本人也只会写asp.net mvc 网站, 所以百度了很多资料, 关于HTML 或者 js 打开摄像头的例子 , 终于做了一个可以正常使用的例子出来。 本人菜鸟,写的不对请见谅。
参考资料:
https://www.jb51.net/html5/422307.html
https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
https://www.jianshu.com/p/e03bd23b6b5c
https://www.cnblogs.com/wenqd/p/11541030.html
https://juejin.cn/post/6844903838822957063
首先在visual studio里面新建一个普通的ASP.net mvc 项目, 然后HomeController 里面加入一个页面actionResult ,比如说 Cam2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SaoMaTest1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Cam2()
{
return View();
}
}
}
Cam2页面的html代码如下
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Cam2</title>
<style>
video {
width: 50%;
height: 50%;
margin: 50px auto;
background-color: aquamarine;
display: block;
}
</style>
</head>
<body>
<video id="video"></video>
<script>
var video = document.getElementById('video');
if (navigator.mediaDevices.getUserMedia) {
//最新的标准API
navigator.mediaDevices.getUserMedia({video : {width: 1000, height: 1000}}).then(success).catch(error);
} else if (navigator.webkitGetUserMedia) {
//webkit核心浏览器
navigator.webkitGetUserMedia({video : {width: 1000, height: 1000}},success, error)
} else if (navigator.mozGetUserMedia) {
//firfox浏览器
navigator.mozGetUserMedia({video : {width: 1000, height: 1000}}, success, error);
} else if (navigator.getUserMedia) {
//旧版API
navigator.getUserMedia({video : {width: 1000, height: 1000}}, success, error);
}
function success(stream) {
//兼容webkit核心浏览器
// let CompatibleURL = window.URL || window.webkitURL;
//将视频流设置为video元素的源
console.log(stream);
//video.src = CompatibleURL.createObjectURL(stream);
video.srcObject = stream;
video.play();
}
function error(error) {
console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
}
</script>
</body>
</html>
在谷歌浏览器或者最新的edge浏览器里面运行就可以看到效果了。
备注:
其实重点是用到html5里面的 <video> 标签,这个视频标签可以用 mediaDevices.getUserMedia 来取得摄像头设备的权限。