电容插件
对于 Ionic 开发人员来说,开始使用电容非常简单。向您的项目添加插件与向项目添加任何您可能需要的依赖项没有什么不同。
安装
要安装插件,请找到您要使用的插件并使用您的包管理器(如 npm)安装它。
# Install the Capacitor Plugins
$ npm install @capacitor/camera
用法
安装后,可以将插件导入到组件中,并直接从代码中调用本机功能。
以 相机插件 为例,首先安装它
- JavaScript
- Angular
- Vue
- React
import { Camera, CameraResultType } from '@capacitor/camera';
const takePicture = async () => {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});
const imageUrl = image.webPath;
imageElement.src = imageUrl;
};
import { Component } from '@angular/core';
import { Camera, CameraResultType } from '@capacitor/camera';
@Component({...})
export class CameraComponent{
public imageSrc: string | undefined = '';
async takePicture() {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});
const imageUrl = image.webPath;
this.imageSrc = imageUrl;
};
}
<template>
...
</template>
<script setup lang="typescript">
import { ref } from 'vue';
import { Camera, CameraResultType } from '@capacitor/camera';
const imageSrc = ref<string | undefined>('');
const takePicture = async () => {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});
const imageUrl = image.webPath;
imageSrc.value = imageUrl;
};
</script>
import { Camera, CameraResultType } from '@capacitor/camera';
import { useState } from 'react';
export function CameraComponent() {
const [imageSrc, setImageSrc] = useState<string | undefined>('');
const takePicture = async () => {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});
const imageUrl = image.webPath;
setImageSrc(imageUrl);
};
return (...)
}