How I Built the Digital Compass
The Digital Compass is a real-time, browser-based compass designed especially for mobile devices. It leverages device orientation sensors to display heading, direction, and rotation with visual clarity. Built using pure HTML, CSS, and JavaScript โ no libraries, no dependencies.
๐ Why I Built It
I wanted to create something practical, fast, and native to the browser โ something that could serve as a quick utility without needing app installs. A compass was the perfect idea: it's useful, sensor-based, and lets me experiment with real-world data handling via the browser.
๐ง How It Works
The project uses the DeviceOrientationEvent and DeviceOrientationAbsoluteEvent to read your deviceโs heading (alpha) in degrees. This value is then used to rotate the compass needle using a CSS transform.
// Example of sensor binding
window.addEventListener("deviceorientationabsolute", (e) => {
const heading = e.alpha;
compassNeedle.style.transform = `rotate(${-heading}deg)`;
});
The visual needle rotates against a circular background. I also calculate and display the nearest cardinal direction (N, NE, E, etc.) using basic math on the angle value.
๐ฑ Design Goals
- Mobile-first, touch-friendly layout
- Live heading display in degrees
- Dynamic cardinal direction text
- Dark mode support via toggle
- Minimal battery and CPU usage
๐จ Tech Stack
- JavaScript โ to handle device orientation and heading logic
- HTML/CSS โ to render the UI and handle transformations
- DeviceOrientation API โ for accessing sensor data in real-time
โ ๏ธ Compatibility Notes
- โ Works best on modern mobile browsers (iOS Safari, Chrome Android)
- โ May not work on desktop or emulators due to sensor unavailability
- ๐ Some devices require explicit permission to access motion data
- ๐ HTTPS is required for sensor access in most browsers
"Building this compass taught me how much modern browsers can do when you dig into their native capabilities." โ Saheef
๐ฎ What's Next?
Iโm exploring the following future upgrades:
- ๐ GPS-aware direction of travel
- โฑ๏ธ Calibration screen for better accuracy
- ๐ฒ Installable PWA with offline support
- ๐งญ Magnetic declination adjustment