AngularJS中使用HTML5手机摄像头拍照的完整攻略如下:
HTML5摄像头API简介
HTML5提供了访问设备摄像头的API,这个API是Navigator.getUserMedia(),它用于打开摄像头,并且访问摄像头捕获的视频流。
实现步骤
- 获取用户摄像头的许可
- 创建一个video元素
- 将摄像头捕获的视频流绑定到video元素上
- 创建一个Canvas元素
- 将video元素的视频绘制在Canvas上
- 从Canvas上获取图像
- 将图像编码成data URI格式的字符串
- 将data URI存储在AngularJS变量中
示例一:使用HTML5实现拍照功能
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>拍照</title>
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<style type="text/css">
video{
width: 100%;
max-width: 300px;
height: auto;
}
canvas{
display: none;
}
img{
max-width: 300px;
height: auto;
}
</style>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<button ng-click="start()">开始拍照</button>
<video id="video" autoplay></video>
<canvas id="canvas"></canvas>
<img ng-src="{{imgSrc}}">
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var video = document.querySelector("#video");
var canvas = document.querySelector("#canvas");
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(function(stream) {
video.srcObject = stream;
})
.catch(function(err) {
console.log("error", err);
});
$scope.start = function(){
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
$scope.imgSrc = canvas.toDataURL();
}
});
</script>
</body>
</html>
示例二:将拍照结果上传至服务器
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>拍照上传</title>
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<style type="text/css">
video{
width: 100%;
max-width: 300px;
height: auto;
}
canvas{
display: none;
}
img{
max-width: 300px;
height: auto;
}
</style>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<button ng-click="start()">开始拍照</button>
<video id="video" autoplay></video>
<canvas id="canvas"></canvas>
<img ng-src="{{imgSrc}}">
<button ng-click="upload()">上传</button>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var video = document.querySelector("#video");
var canvas = document.querySelector("#canvas");
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(function(stream) {
video.srcObject = stream;
})
.catch(function(err) {
console.log("error", err);
});
$scope.start = function(){
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
$scope.imgSrc = canvas.toDataURL();
}
$scope.upload = function(){
var dataUrl = $scope.imgSrc.replace(/^data:image\/(png|jpg);base64,/, "");
$http.post('/api/uploadImage', dataUrl)
.then(function(response) {
console.log("success", response);
}, function(response) {
console.log("error", response);
});
}
});
</script>
</body>
</html>
以上就是使用HTML5摄像头API实现拍照功能的攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:AngularJS中使用HTML5手机摄像头拍照 - Python技术站