微信小程序自定义相机(React+Taro)

1、index.tsx

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(false)
  const [devicePosition,setDevicePosition] = useState('front')
  const [path,setPath] = useState('')
  const [showBg,setShowBg] = useState(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 (
    
      {showImage?
      
        
          
            {showBg?:}
          
        
        
          { setShowImage(false) }}>返回
          {showBg?拍照:重拍}
          { setDevicePosition(devicePosition=='front'?'back':'front') }}>切换前后置
        
      
      :调用相机
      }
    
  );
});

export default Home;

2、scss

.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

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);
          },
        })
      }
    })
  });
}

你可能感兴趣的:(微信小程序,数码相机,react.js)