原生js 调用电脑摄像头完成拍照

原生js 调用电脑摄像头完成拍照

1 ,完成拍照后可转换成base64码,你可以对当前base64码进行操作,当初我就利用这个功能点完成前端的人脸登录的,拿到base码后你可以post传入后台,将当前base64码转换成图片,之后调用百度api,或者腾讯api人脸识别进行对比
2,上代码

DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>title>
	head>
	<body>

	<video id="video" width="500" height="500">video>
	<canvas id="canvas" width="500" height="500">canvas>
	
	<a href="javascript:saveFile(filename)" onclick="dd()">点击我a>
	
	<div id="box">
		
	div>
	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)
			}
		}
		
		let video = document.getElementById('video');
		let canvas = document.getElementById('canvas');
		let context = canvas.getContext('2d');
		//成功回调
		function success(stream){
			video.srcObject = stream;
			video.play();
		}
		//失败回调
		function error(error) {
			console.log("访问用户媒体失败");
		}
		//开启摄像头
		if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
			getUserMedia({video:{width:500,height:500}},success,error)
		}else {
			alert("不支持");
		}
		//实现拍照的功能
		function dd(){
			
			context.drawImage(video,0,0,500,500);
		
		}
		
		
		//下面的代码是保存canvas标签里的图片并且将其按一定的规则重命名
	var type = 'jpg';
	var _fixType = function(type) {
    type = type.toLowerCase().replace(/jpg/i, 'jpeg');
    var r = type.match(/png|jpeg|bmp|gif/)[0];
    return 'image/' + r;
    };

	var saveFile = function(filename){
	//获取canvas标签里的图片内容
	var imgData = document.getElementById('canvas').toDataURL(type);
	imgData = imgData.replace(_fixType(type),'image/octet-stream');
	
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = imgData; //base64码
    save_link.download = filename;//图片名称
	
	var divbox=document.getElementById("box");
	divbox.innerText=imgData;
   
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);

};
   
// 下载后的文件名规则
	var filename =11111+ '.' + type;
	script>
html>

你可能感兴趣的:(java,javascript,前端,html5,人脸识别,java)