1、index.tsx
javascript
import { useState } from 'react'
import { View, Image, Camera } from "@tarojs/components";
import { observer } from "mobx-react";
import { AtButton } from 'taro-ui'
import "./index.scss";
import { takePhote } from '@/common/bluetoolth/tool'
const Home = observer(() => {
const [showImage,setShowImage] = useState<boolean>(false)
const [devicePosition,setDevicePosition] = useState<any>('front')
const [path,setPath] = useState<string>('')
const [showBg,setShowBg] = useState<boolean>(true)
const openMedia = async ()=>{
console.log('检测-拍照')
setShowImage(true)
}
const takePhoto = async ()=>{
console.log('相机拍照时触发')
const res = await takePhote()
console.log('照片path',res.path)
setPath(res.path)
setShowBg(false)
}
const resetPhoto = ()=>{
setPath('')
setShowBg(true)
}
return (
<View className="home-wrap">
{showImage?
<View className='camera-box'>
<Camera className='camera-photo' mode='normal' devicePosition={devicePosition}>
<View className='camera-path-box'>
{showBg?<View className='bg'></View>:<Image className='camera-path' src={path}></Image>}
</View>
</Camera>
<View className='camera-button'>
<View onClick={()=>{ setShowImage(false) }}>返回</View>
{showBg?<View onClick={takePhoto}>拍照</View>:<View onClick={resetPhoto}>重拍</View>}
<View onClick={()=>{ setDevicePosition(devicePosition=='front'?'back':'front') }}>切换前后置</View>
</View>
</View>
:<AtButton type='primary' size='normal' onClick={openMedia}>调用相机</AtButton>
}
</View>
);
});
export default Home;
2、scss
css
.home-wrap {
padding-top: 100px;
.camera-box {
width: 100%;
height: calc(100vh - 100px);
.camera-photo {
height: calc(100% - 200px);
.camera-path-box {
width: 100%;
height: 100%;
.camera-path {
width: 100%;
height: 100%;
}
.bg {
background: url($IMG_URL + "/home/home-top-bg.png") 0 0 no-repeat;
background-size: contain;
width: 100%;
height: 100%;
}
}
}
.camera-button {
height: 200px;
display: flex;
justify-content: space-between;
background-color: #ffffff;
align-items: center;
}
}
}
3、tool.js
javascript
export function takePhote() {
const ctx = wx.createCameraContext()
const that = this
return new Promise((resolve, reject) => {
ctx.takePhoto({
quality: 'high',
success: (res) => {
wx.getImageInfo({
src: res.tempImagePath,
success:res=>{
console.log(res)
resolve(res);
},
fail(res) {
reject(res);
},
})
}
})
});
}