← Back to Blog
Tutorial2 min read

Real-Time Face Detection with JavaScript and a Cloud API

Build real-time face detection in the browser using JavaScript, webcam capture, and the ARSA Face Recognition API — with age, gender, and liveness.

What We're Building

A browser-based face detection app that captures frames from the webcam, sends them to the ARSA Face Recognition API, and displays results including age, gender, and liveness status.

HTML Setup

html
<video id="webcam" autoplay playsinline width="640" height="480"></video>
<canvas id="canvas" style="display:none"></canvas>
<div id="results"></div>
<button onclick="detectFace()">Detect Face</button>

Start Webcam

javascript
const video = document.getElementById('webcam');

async function startWebcam() {
  const stream = await navigator.mediaDevices.getUserMedia({
    video: { width: 640, height: 480 }
  });
  video.srcObject = stream;
}

startWebcam();

Capture and Analyze

javascript
const API_KEY = "your-api-key";

async function detectFace() {
  // Capture frame
  const canvas = document.getElementById('canvas');
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  canvas.getContext('2d').drawImage(video, 0, 0);
  
  // Convert to blob
  const blob = await new Promise(resolve => {
    canvas.toBlob(resolve, 'image/jpeg', 0.8);
  });
  
  // Send to API
  const formData = new FormData();
  formData.append('face_image', blob, 'capture.jpg');
  
  const response = await fetch(
    'https://faceapi.arsa.technology/api/v1/face_analytics',
    {
      method: 'POST',
      headers: { 'x-key-secret': API_KEY },
      body: formData
    }
  );
  
  const data = await response.json();
  displayResults(data);
}

function displayResults(data) {
  const div = document.getElementById('results');
  if (data.faces && data.faces.length > 0) {
    const face = data.faces[0];
    div.innerHTML = `
      <p>Age: ${face.age}</p>
      <p>Gender: ${face.gender} (${(face.gender_probability * 100).toFixed(1)}%)</p>
      <p>Real face: ${face.passive_liveness.is_real_face}</p>
    `;
  } else {
    div.innerHTML = '<p>No face detected</p>';
  }
}

Continuous Detection

For real-time detection, call the API on an interval:

javascript
let detecting = false;

async function continuousDetection() {
  if (detecting) return;
  detecting = true;
  await detectFace();
  detecting = false;
}

// Detect every 2 seconds
setInterval(continuousDetection, 2000);

Next Steps

  • Python integration guide
  • React Native mobile app
  • Build a face login system
  • API documentation
  • Start free with 100 API calls per month.

    Ready to get started?

    Try ARSA Face Recognition API free with 100 API calls/month.

    Start Free Trial