Cordova 是用于使用web技术(HTML,CSS、JS)以及平台原生语言构建跨平台的混合App应用工具链。我们可以认为Cordova是一个容器,(在app中嵌入一个轻量级浏览器webview),用于将我们的应用程序与本机功能连接。默认情况下,Web应用程序不能使用本机移动功能。这就是Cordova派上用场的地方。它为web应用和移动设备之间的连接提供了桥梁,(jsBridge)。 通过使用Cordova,我们可以使混合移动应用程序使用摄像头、地理位置、文件系统和其它本地移动功能。
本文实现一个基本的功能,使用js通过Cordova API调用原生的摄像头功能拍照后并显示在界面上。首先创建一个工程:
Cordova可以开发出跨平台的app,我们这里以Android app为例,添加Android平台支持:
cd hello
cordova platform add android
当然还可以添加对IOS与Windows上app的支持。
添加Camera插件:
cordova plugin add cordova-plugin-camera
下面是cordova-plugin-camera插件的使用介绍:
注:上面说明了只有在"deviceready"事件执行结束后才能调用cordova-plugin-camera插件。"deviceready"事件结束相当于页面加载完后,Cordova环境准备好了后,就会触发onDeviceReady()。
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
上面的camera对象调用拍照功能中,前两个参数为回调函数,最后一个参数为摄像头参数。
在www文件夹根目录下修改index.html文件,添加“拍照”按钮以及相应的图片显示标签,内容如
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<div class="app">
<h1>Hello World</h1>
<h2>王枫的第一个app</h2>
<button id="btn">拍照</button>
<br />
<img id="img1" width="100" />
</div>
<script type="text/javascript" src="cordova.js"></script>
<!-- <script type="text/javascript" src="js/index.js"></script> -->
<script type="text/javascript" src="js/myIndex.js"></script>
</body>
</html>
在js目录下创建myIndex.js文件:
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
console.log(navigator.camera);
//获得按钮,添加点击事件执行拍照
document.getElementById('btn').onclick=function(){
//调用起Cordova中的照相机插件进行拍照
navigator.camera.getPicture(onSuccess, onError, {
});
function onSuccess(imageURI){
alert('调用成功');
console.log('console log: 调用成功');
alert(imageURI);
console.log('console log: '+imageURI);
document.querySelector('img').src=imageURI;
}
function onError(){
alert('调用失败');
}
}
}