使用html打开电脑前置摄像头并拍照

使用html打开电脑前置摄像头,并拍照

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
    <video id="video" width="300" height="300" poster="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F01%2F14%2F62%2F59043cebb703f_610.jpg&refer=http%3A%2F%2Fpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637115934&t=cd4ebc01b4b11fb45ce65a3b2dc7e933"></video>
	<canvas id="canvas" width="300" height="300"></canvas><br>
    <button id="camera">摄像头</button><button id="snap">拍照</button>
</body>
<script>
    	//用来匹配不同的浏览器
		function getUserMedia(constraints,success,error){
			if(navigator.mediaDevices.getUserMedia){
				navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
			}else if (navigator.webkitGetUserMedia) {
				navigator.webkitGetUserMedia(constraints,success,error);
			}else if (navigator.mozGetUserMedia) {
				navigator.mozGetUserMedia(constraints,success,error);
			}else if (navigator.getUserMedia) {
				navigator.getUserMedia(constraints,success,error)
			}
		}

		//成功回调
		function success(stream){
			video.srcObject = stream;
			video.play();
		}
		//失败回调
		function error(error) {
			console.log("访问用户媒体失败");
		}

        document.getElementById('camera').addEventListener('click',function(){
			//视频窗口尺寸
            let size = 300;
            let video = document.getElementById('video');
            let canvas = document.getElementById('canvas');
            let context = canvas.getContext('2d');

            //开启摄像头
            if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
                getUserMedia({video:{width:size,height:size}},success,error)
            }else {
                alert("不支持");
            }
            //实现拍照的功能
            document.getElementById('snap').addEventListener('click',function(){
                context.drawImage(video,0,0,size,size);
            });

		});
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值