DEV Community

Stop Slouching! Build a Real-Time Pose Tracker for Better Neck Health with MediaPipe and React

We’ve all been there: deeply immersed in a debugging session, only to realize four hours later that our necks are tilted at a 45-degree angle, resembling a questioning pigeon.

"Tech Neck" isn't just a meme; it’s a genuine ergonomic crisis for developers. In this tutorial, we are going to build a real-time pose estimation application that runs entirely in your browser.

Using MediaPipe, WebAssembly (Wasm), and React, we will track skeletal keypoints to calculate your cervical spine angle and alert you when your posture sucks. 💻

By leveraging edge computing via Wasm, we ensure that your video data never leaves your machine, keeping your privacy intact while maintaining high-performance, low-latency detection.

The Architecture: From Pixels to Posture

To achieve 60 FPS in a web browser without freezing the UI, we need a clean pipeline. We use MediaPipe’s pre-trained models compiled to WebAssembly for heavy lifting.

graph TD A[Webcam Feed] --> B[React Camera Component] B --> C[WebAssembly MediaPipe Engine] C --> D[Landmark Detection - 33 Points] D --> E[Cervical Angle Calculation Logic] E --> F{Angle > Threshold?} F -- Yes --> G[Trigger Alert UI] F -- No --> H[Healthy State] G --> I[Real-time Feedback Loop] H --> I

Prerequisites

Before we dive in, ensure you have the following:

  • Tech Stack: React (v18+), TypeScript, and the @mediapipe/pose package.
  • Math Skills: Basic trigonometry (we’re calculating angles between points!).

Step 1: Setting up the MediaPipe Hook

First, we need to initialize the MediaPipe Pose model. Since loading the Wasm binaries can be heavy, we’ll handle this inside a custom React hook to keep our component clean.

import { useEffect, useRef } from 'react';
import { Pose, Results } from '@mediapipe/pose';

export const usePoseDetection = (onResults: (results: Results) => void) => {
  const poseRef = useRef<Pose | null>(null);
  useEffect(() => {
    const pose = new Pose({
      locateFile: (file) => `https://cdn.jsdelivr.net/npm/@mediapipe/pose/${file}`,
    });
    pose.setOptions({
      modelComplexity: 1,
      smoothLandmarks: true,
      minDetectionConfidence: 0.5,
      minTrackingConfidence: 0.5,
    });
    pose.onResults(onResults);
    poseRef.current = pose;
    return () => pose.close();
  }, []);
  return poseRef;
};

Step 2: Calculating the "Cervical Tilt"

To detect a slouch, we focus on three landmarks: the Ear, the Shoulder, and a vertical reference line. The angle between your ear and shoulder relative to the vertical axis is a prime indicator of "Forward Head Posture."

// Geometric logic to calculate the angle
const calculateAngle = (p1: any, p2: any) => {
  const radians = Math.atan2(p2.y - p1.y, p2.x - p1.x);
  let angle = Math.abs((radians * 180.0) / Math.PI);
  // We want the angle relative to the vertical line (90 degrees)
  return Math.abs(90 - angle);
};

// Inside your result handler:
const ear = results.poseLandmarks[7]; // Left Ear
const shoulder = results.poseLandmarks[11]; // Left Shoulder
const neckAngle = calculateAngle(ear, shoulder);
if (neckAngle > 25) {
  console.warn("🚨 Sit up straight! Your neck is straining.");
}

Step 3: Integrating with the React UI

We need a canvas to draw the skeletal overlay and a video element to capture the stream. For production-grade performance, you should consider running the calculateAngle logic inside a Web Worker to keep the main thread buttery smooth.

import React, { useRef } from 'react';
import Webcam from 'react-webcam';

const PoseMonitor: React.FC = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const onResults = (results: Results) => {
    if (!canvasRef.current) return;
    const canvasCtx = canvasRef.current.getContext('2d');
    // 1. Draw the video frame to canvas
    // 2. Draw MediaPipe connectors (Landmarks)
    // 3. Overlay the Angle text
    drawPostureOverlay(canvasCtx, results);
  };
  const poseRef = usePoseDetection(onResults);
  return (
    <div className="relative">
      <Webcam onUserMedia={() => { /* Start Pose.send() loop */ }} />
      <canvas ref={canvasRef} className="absolute top-0 left-0" />
      <div className="status-bar">
        {isSlouching ? "⚠️ Fix Your Posture" : "✅ Looking Good!"}
      </div>
    </div>
  );
};

Advanced Patterns & Production Readiness 🥑

While this demo gets you started, building a robust health-tech tool requires handling edge cases like low lighting, varying camera angles, and user calibration.

For more production-ready examples and advanced AI patterns-such as integrating these metrics into a full-stack dashboard or using Pydantic for data validation in AI pipelines-check out the deep-dive articles over at WellAlly Tech Blog. They cover how to scale these "Learning in Public" projects into enterprise-grade wellness solutions.

Conclusion

By combining MediaPipe’s Wasm-powered inference with React’s reactive UI, we’ve built a tool that helps developers stay healthy while doing what they love.

Next Steps:

  • Add a "Pomodoro" timer that only ticks when your posture is correct.
  • Use the Web Storage API to track your "Slouch Score" throughout the day.
  • Implement a desktop notification using the Notification API.

Stop slouching, start coding, and stay healthy! If you found this helpful, drop a comment below or share your "Slouch Score"! 🚀✨

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.