@@ -58,6 +58,9 @@ import {
5858 emailUserRecipeSection ,
5959} from "./js_utilities/query_selector.js" ;
6060
61+ let currentCameraIndex = 0 ;
62+ const switchCameraButton = document . getElementById ( 'switchCamera' ) ;
63+
6164
6265
6366wantToTakeAPicture . addEventListener ( "click" , ( ) => {
@@ -252,15 +255,63 @@ recipeButtons.forEach((button) => {
252255} ) ;
253256
254257// Picture section
255- navigator . mediaDevices
256- . getUserMedia ( constraint )
257- . then ( ( stream ) => {
258+
259+
260+ async function getVideoDevices ( ) {
261+ const devices = await navigator . mediaDevices . enumerateDevices ( ) ;
262+ return devices . filter ( device => device . kind === 'videoinput' ) ;
263+ }
264+
265+ async function startCamera ( deviceId ) {
266+ const constraints = {
267+ audio : false ,
268+ video : {
269+ deviceId : deviceId ? { exact : deviceId } : undefined ,
270+ width : { min : 1024 , ideal : 1280 , max : 1920 } ,
271+ height : { min : 576 , ideal : 720 , max : 1080 }
272+ }
273+ } ;
274+
275+ try {
276+ const stream = await navigator . mediaDevices . getUserMedia ( constraints ) ;
258277 video . srcObject = stream ;
259- video . play ( ) ;
260- } )
261- . catch ( ( error ) => {
278+ await video . play ( ) ;
279+ } catch ( error ) {
262280 console . error ( "Error accessing camera:" , error ) ;
263- } ) ;
281+ }
282+ }
283+
284+ async function initializeCamera ( ) {
285+ const videoDevices = await getVideoDevices ( ) ;
286+
287+ if ( videoDevices . length > 1 ) {
288+ switchCameraButton . style . display = 'block' ;
289+ switchCameraButton . addEventListener ( 'click' , ( ) => {
290+ currentCameraIndex = ( currentCameraIndex + 1 ) % videoDevices . length ;
291+ startCamera ( videoDevices [ currentCameraIndex ] . deviceId ) ;
292+ } ) ;
293+ } else {
294+ switchCameraButton . style . display = 'none' ;
295+ }
296+
297+ // Start with the rear camera if available
298+ const rearCameraDevice = videoDevices . find ( device => device . label . toLowerCase ( ) . includes ( 'back' ) || device . label . toLowerCase ( ) . includes ( 'rear' ) ) ;
299+ startCamera ( rearCameraDevice ? rearCameraDevice . deviceId : videoDevices [ 0 ] . deviceId ) ;
300+ }
301+
302+ initializeCamera ( ) ;
303+
304+
305+
306+ // navigator.mediaDevices
307+ // .getUserMedia(constraint)
308+ // .then((stream) => {
309+ // video.srcObject = stream;
310+ // video.play();
311+ // })
312+ // .catch((error) => {
313+ // console.error("Error accessing camera:", error);
314+ // });
264315
265316function capturePhoto ( ) {
266317 context . drawImage ( video , 0 , 0 , 400 , 100 ) ;
0 commit comments