How can I easily swap between the front and back cameras while using an app?

Trying to create a web-ar experience that allows users to switch between front and back cameras while utilizing SLAM/6dof with the back camera has been a challenging endeavor. While attempting this in PlayCanvas, I faced difficulties getting the front camera to function properly. Similarly, my efforts in A-Frame have resulted in some success, but various issues persist.

The lack of specific PlayCanvas documentation on enabling the front camera led me to experiment with XR.stop() followed by XR.run({canvas: document.getElementById('camerafeed'), cameraConfig: {direction: XR.XrConfig.camera().FRONT}}), unfortunately without any noticeable effect.

Meanwhile, within A-Frame, I managed to activate the front camera, albeit encountering log errors, rendering issues with 3D objects, and complications when attempting to switch cameras multiple times.

In addition, attempts to toggle SLAM/6dof parameters have been met with an error message indicating that disableWorldTracking cannot be altered after XR.run has been executed, even following the use of XR.stop() and stopxr event listening.

Snippet of A-Frame functionality for switching to the front camera:

init: function() {
this.el.sceneEl.addEventListener('stopxr', event => {
      console.log("AR has been stopped.");
      const videoCanvas = document.querySelector('canvas.a-canvas');
      XR.XrController.configure({disableWorldTracking: true});
      XR.run({canvas: videoCanvas, cameraConfig: {direction: XR.XrConfig.camera().FRONT}});
    });
},

switchToFace: function() {
    this.el.sceneEl.emit('stopxr');
    //XR.stop();
  },

What is the correct procedure for adjusting the disableWorldTracking parameter while the scene is active? And how can the seamless transition between front and back cameras be achieved during runtime?

Answer №1

Following a discussion with a developer from 8th wall, it was confirmed that only one XR session is supported per page. This means that after calling XR.stop, XR.run cannot be invoked again. However, there is an alternative method to switch between the front and back cameras while still maintaining SLAM functionality.

  1. Listen for the onCameraStatusChange event and store references to the stream and video elements.
  2. When initiating the camera swap, temporarily pause 8th wall using XR.pause().
  3. Stop all tracks in the stream obtained from the first step.
  4. Utilize
    navigator.mediaDevices.getUserMedia(constraints);
    to acquire the stream for the desired camera.
  5. Assign the new stream to the video element saved in step 1.
  6. Monitor the video element for the playing event and then resume 8th wall by calling XR.resume();

It should be noted that SLAM functionality will only work if you initially start with the back camera. After switching to the front camera and back again, SLAM will cease to function.

Answer №2

With the latest update (13.1 release), it is now possible to pause and resume XR sessions. By using XR8.stop() followed by XR8.run(), you can change the camera direction as needed.

If you are working on an AFrame project with 8th Wall, simply remove the xrweb component from your <a-scene> to halt XR functionality. To restart, add it back with a new cameraDirection parameter if desired.

Check out these projects demonstrating how to switch camera directions:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

IE9 does not consider JavaScript variable as undefined

Hello, I came across this JS code written by someone else: function somename(f) var procName = ""; var procParams = new Array(); var parseEl = ""; var parseEls = new Array(); var parseInd = 0; var procParamsInd = 0; var IsVal ...

What indicators should we look for to decide if JavaScriptExecutor is needed in a Selenium C# project?

Encountering an exception with TestInChrome1 - "OpenQA.Selenium.ElementNotInteractableException: element not interactable". On the other hand, using JavaScriptExecutor in TestInChrome2 resolves the issue. Some key questions arise: What is causing the ...

Update the link to a KML file used by Google Maps when a button is clicked

On the initial page load, I want to showcase an 8 Day Average KML file on Google Maps. However, users should have the option to click on the "1 Day" and "3 Day" buttons to switch the reference in Google Maps from the "8 Day" file. The aim is to design a s ...

I am unable to retrieve information from Firebase in Vue

Currently, I am following a tutorial on YouTube to enhance my knowledge about storing data in Firebase and then utilizing it in a Vue application. (You can watch the tutorial at this link: https://www.youtube.com/watch?v=Htt8AKeF1Kw, you will encounter the ...

Form calculation

An issue has arisen with my calculating form for a client where an incorrect amount is displayed when 0.93 is entered into the percentage box. Original calculation: 10 x 10 x 15 x 0.93 = 13.95 Corrected calculation: 10 x 10 x 15 x 0.93 = 1.395 I am seek ...

Creating a cube with unique textures on each face in three.js r81: What's the best way to achieve this?

After updating to the latest version of three.js, I encountered an issue where THREE.ImageUtils.loadTexture no longer works. As a result, I tried searching for examples of cubes with different faces, but they all utilized the outdated technique "new THREE. ...

Page elements subtly move when reloading in Chrome

I am experiencing an issue with a div that has left and top offsets randomly selected from an array of values upon page load. Most of the time, it works fine. However, occasionally, upon refreshing the page, the window scrolls down slightly, revealing the ...

Automated task scheduled to execute every minute between the hours of 8am and 4.30pm using Cloudwatch Events

I am facing an issue with my working CRON schedule. It currently runs from 8am to 5pm and I need to change it to end at 4:30pm. Is it possible to set a specific half-hour time interval in CRON? Below is the current setting for my CRON: 0/1 8-17 ? * MON- ...

What is the regular expression that allows numbers between 1 and 24, including decimals?

Can anyone help me create a regex expression that only allows numbers between 1 and 24, with up to 2 decimal places? The numbers should range from 1 to 24, as well as include decimals like 1.00, 1.01, 1.02, all the way up to 24.99. ...

Utilize webpack to import functions from separate files

I am looking to streamline the process of importing and using functions from a different file. Ideally, I would like to simply call these functions by their name without any extra prefixes or naming conventions. However, I am aware that using eval() can po ...

Developing novel errors in JavaScript

There are times when I overlook using the await keyword, for example: const foo = bar(); // as opposed to const foo = await bar(); Identifying these bugs can be challenging. Are there any methods, libraries, or tools that can help prevent such errors? ...

Customizing the layout of specific pages in NextJSIncorporating

In my Next.js project, I'm trying to set up a header and footer on every page except for the Login page. I initially created a layout.tsx file in the app directory to apply the layout to all pages, which worked fine. However, when I placed another lay ...

Implementing react router functionality with Material-UI tabs

Could you please provide some insight on how to integrate my routes with MUI tabs? I'm not very familiar with MUI and could use some guidance on how to get it working. Any suggestions would be appreciated. To simplify the code, I have removed the imp ...

Modifying the temp variable by assigning a new value to this.value in Javascript

Using a temporary variable, I initialize a THREE.Vector3 which is then passed into the creation of an object. object[i] = new Object(new THREE.Vector3(0,0,0)); Within the Object class, there is a variable called texture that gets assigned the new THREE.V ...

I'm having trouble getting $.getJSON to function properly

Has anyone encountered issues with the getJSON function in jQuery? function loadJSON(){ console.log("loading JSON") var jsonFile = themeURL+"/map.json" $.getJSON(jsonFile, function(data){ console.log("loaded JSON") $("#infobox").fadeOut(1000 ...

Tips for customizing the WooCommerce product page

If you want to customize the layout of a WooCommerce product page, you can override the template by copying the WooCommerce template folder into your theme. You can find step-by-step instructions here. I am looking to change the layout of a WooCommerce pr ...

Storing a selected database column as a variable from an HTML page in Node.js with Express

My website showcases flight information pulled from a MySQL database. The process begins with a form where users select destinations and dates for their desired flight. Once the form is submitted, users are directed to another page where flights matching t ...

In React Native, the onPress handler will continue to be triggered indefinitely after 2-3 presses

import firebase from './Firebase'; import { useState, useEffect } from 'react'; import { StyleSheet, Text, View, Button, FlatList } from 'react-native'; import { TextInput } from 'react-native-web'; import { setStatu ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

Warning: React Element creation caution with flow-router integration

Whenever I incorporate the following code into my Meteor app: Home = FlowRouter.route("/", { name: "App", action(params) { ReactLayout.render(App); } }); An error message pops up in the Chrome console: Warning: React.createElement: type shoul ...