Ambient Light
The Ambient Light API allows Web applications to access the light intensity level measured by the device's light sensor, normally built-in with the device's camera.
The first approach to supporting light intensity sensor on the Web - as a standalone API - was implemented in Firefox back in 2013. Since then the specification was rewritten to make use of the new Generic Sensors API. This flavor, as of early 2020, is only experimentally implemented in Google Chrome, behind the "Generic Sensor Extra Classes" flag.
API glimpse
The old, standalone API
window.addEventListener('devicelight', listener)
- An event fired when the device's light sensor measured value has changed, containing the light intensity expressed in lux.
The new, generic API
sensor = new AmbientLightSensor()
- Creates an object serving as an accessor to the light intensity sensor readings.
sensor.addEventListener('reading', listener)
- An event fired when the light intensity reading has changed, indicating that the sensor object contains updated light intensity expressed in lux, in
sensor.illuminance
property. sensor.start()
- Starts listening for the sensor readings.
Live Demo
Current light intensity is unknown.
-
function update(illuminance) { document.getElementById("value").innerHTML = illuminance + " lux"; var colorPart = Math.min(255, illuminance).toFixed(0); document.getElementById("box").style.backgroundColor = "rgb(" + colorPart + ", " + colorPart + ", " + colorPart + ")"; } if ("AmbientLightSensor" in window) { try { var sensor = new AmbientLightSensor(); sensor.addEventListener("reading", function (event) { update(sensor.illuminance); }); sensor.start(); } catch (e) { console.error(e); } } if ("ondevicelight" in window) { function onUpdateDeviceLight(event) { update(event.value); } window.addEventListener("devicelight", onUpdateDeviceLight); }
-
<p>Current light intensity is <b id="value">unknown</b>.</p> <div id="box"></div>