Skip to main content
Platform
Camera Kit Web

Switching Between Front and Back Cameras

When your web application is used on mobile devices, you might want to allow the user to switch between the front and back camera.

index.html
<html>
<head>
<title>Switching Between Front and Back Cameras</title>
</head>
<body>
<canvas id="canvas"></canvas>
<span id="flip"></span>
<script type="module" src="script.ts"></script>
</body>
</html>
script.ts
import {
bootstrapCameraKit,
CameraKitSession,
createMediaStreamSource,
Transform2D,
} from '@snap/camera-kit';

const liveRenderTarget = document.getElementById('canvas') as HTMLCanvasElement;
const flipCamera = document.getElementById('flip');

let isBackFacing = true;
let mediaStream: MediaStream;

async function init() {
const cameraKit = await bootstrapCameraKit({
apiToken: '<API_TOKEN>',
});

const session = await cameraKit.createSession({ liveRenderTarget });
const { lenses } = await cameraKit.lensRepository.loadLensGroups([
'<LENS_GROUP_ID>',
]);

session.applyLens(lenses[0]);

bindFlipCamera(session);
}

function bindFlipCamera(session: CameraKitSession) {
flipCamera.style.cursor = 'pointer';

flipCamera.addEventListener('click', () => {
updateCamera(session);
});

updateCamera(session);
}

async function updateCamera(session: CameraKitSession) {
isBackFacing = !isBackFacing;

flipCamera.innerText = isBackFacing
? 'Switch to Front Camera'
: 'Switch to Back Camera';

if (mediaStream) {
session.pause();
mediaStream.getVideoTracks()[0].stop();
}

mediaStream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: isBackFacing ? 'environment' : 'user',
},
});

const source = createMediaStreamSource(mediaStream, {
// NOTE: This is important for world facing experiences
cameraType: isBackFacing ? 'back' : 'front',
});

await session.setSource(source);

if (!isBackFacing) {
source.setTransform(Transform2D.MirrorX);
}

session.play();
}

init();
Was this page helpful?
Yes
No