Search code examples
javascriptexpovue-native

How to capture a photo with expo-camera using vue native?


I am new to vue native and im trying to create a page on the app where i can use the camera and capture & show a photo using the expo-camera directive.

This is what i have done:

<template>
  <view class="view-container">

    <view class="container">
       <text>Camera screen</text>
       <camera class="container" :type="this.type" />
       <touchable-opacity 
       class="camera-touchable-opacity"
       :on-press="capturePic"
       >
     </view>

     <view class="home-btn">
        <button title="Go to home screen" @press="goToHomeScreen"></button>
     </view>
  </view>
</template>

<script>
import * as Permissions from 'expo-permissions';
import { Camera } from 'expo-camera';

export default {
  props: {
    navigation: { type: Object }
  },
  data: function() {
    return {
       hasCameraPermission: false,
       type: Camera.Constants.Type.back,
    };
  },
  mounted: function() {
     Permissions.askAsync(Permissions.CAMERA)
       .then(status => {
           hasCameraPermission = status.status == "granted" ? true : false;
       }).catch((err)=>{
           console.log(err);
       });
  },
  components: { Camera },
  methods: {
    goToHomeScreen() {
      this.navigation.navigate("Home");
    },
    capturePic: async function() {
      if(!camera) return
      const photo = await camera.takePictureAsync();
    }
  }
}
</script>

i receive this warning: [Unhandled promise rejection: ReferenceError: Can't find variable: camera]

I don't know what i need since i didn't find anything regarding capturing a photo in the docs.


Solution

  • You can refer your camera as this.$refs.camera in your method, since you need to have a reference on the element as ref="camera" in your code..

    <camera class="container" :type="this.type" ref="camera"/>
    

    The capture function will be this.$refs.camera.takePictureAsync()

    In your code

    capturePic: async function() {
      if(!camera) return
      const photo = await camera.takePictureAsync();
    }