你可以通过运行安装插件:
$ cordova plugin add org.apache.cordova.camera
现在您已经安装了插件,您可以在 Javascript 中使用相机 API:
function takePicture() {
navigator.camera.getPicture(function(imageURI) {
// imageURI is the URL of the image that we can use for
// an <img> element or backgroundImage.
}, function(err) {
// Ruh-roh, something bad happened
}, cameraOptions);
}
这将提示用户拍照,并返回图片的本地 URL,然后您可以在标签内使用该 URL 或用于 CSS 背景图片。
您可以使用下面的代码对相机插件进行简单的包装,以便轻松地异步抓取照片:
module.factory('Camera', ['$q', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
// Do any magic you need
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
} } }]);
这个工厂可以像这样在你的控制器中使用:
.controller('MyCtrl', function($scope, Camera) {
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
console.log(imageURI);
}, function(err) {
console.err(err);
});
};
调用 getPhoto() 时会打开相机(例如,通过单击按钮)。
根据您如何从相机请求数据并在 Angular 标记中使用它,您可能必须将图像 URL 列入白名单,以便 Angular 允许使用 file:// URL(例如,如果您使用 ng-src标签):
module.config(function($compileProvider){
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
})