记录一下Cordova是如何使用插件的,本篇以相机插件为例,官方文档地址
点击查看
新建Cordova应用
$ cordova create camera-demo come.cris.camera cameraDemo
PS:依次对应文件夹名,包名,应用名
添加安卓平台
$ cordova platform add android --save
添加camera插件
$ cordova plugin add cordova-plugin-camera
使用cordova platform ls和cordova plugin ls命令可检查当前平台设置状况以及安装的插件
使用方法
官方提供了这些API我们可以做一个简单的demo,这里使用的是根目录下www文件夹下的文件
www/index.html
// index.html
<!DOCTYPE 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="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<title>Hello World</title>
<style>
.block {
width: 100%;
padding: 10px;
}
#img {
height: 220px;
}
</style>
</head>
<body>
<div class="app">
<div class="block">
<button id="openCamera">按钮</button>
</div>
<div class="block">
<img id="img" />
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
www/index.js
// index.js
var app = {
// Application Constructor
initialize: function () {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function () {
this.receivedEvent('deviceready');
},
// 获取id的函数
$: function (id) {
return document.getElementById(id);
},
// Update DOM on a Received Event
receivedEvent: function () {
var cameraButton = this.$('openCamera');
var _this = this; // this表示当前对象,_this表示cameraButton对象
cameraButton.onclick = function () {
// 打开图片库
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50, // 相片质量是50
sourceType: Camera.PictureSourceType.CAMERA, // 设置从摄像头拍照获取
destinationType: Camera.DestinationType.FILE_URI // 以文件路径返回
});
function onSuccess(imageURI) {
var image = _this.$('img');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
}
};
app.initialize();
运行
$ cordova run android
就可以实现点击拍照并显示图片的功能啦~
代码地址 https://github.com/smileCris/Cordova-plugin-camera
结合dva使用插件开发可见 Cordova+Dva+antd-mobile实现react移动端开发