HTML5 打开摄像头

近来做了一个手机扫码的网页应用, 由于没有其他载体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 来取得摄像头设备的权限。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值