Created
July 7, 2022 21:50
-
-
Save acropup/bd1f2b64832f76ff3e0bb4996bad2c32 to your computer and use it in GitHub Desktop.
webcam manual focus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This uses the html5 MediaStream Image Capture API to manually control focus of the | |
// active webcam or phone camera. | |
// https://w3c.github.io/mediacapture-main/#dom-mediastreamtrack | |
// https://w3c.github.io/mediacapture-image/#mediatracksupportedconstraints-section | |
let videoElem = document.querySelector('video'); | |
let track = videoElem.srcObject.getVideoTracks()[0]; | |
let cap = track.getCapabilities(); | |
console.info('focusMode: ', cap.focusMode); | |
if (cap.focusMode?.includes('manual')) { | |
console.info('focusDistance: ', cap.focusDistance); | |
let { max, min, step } = cap.focusDistance; | |
// To focus as close as possible: | |
await track.applyConstraints({ advanced: [{ focusMode: 'manual', focusDistance: max }] }); | |
// To focus at infinity: | |
await track.applyConstraints({ advanced: [{ focusMode: 'manual', focusDistance: min }] }); | |
// To restore automatic focusing: | |
// await track.applyConstraints({ advanced: [{ focusMode: 'continuous' }] }); | |
} | |
// Note: I've found that with at least one camera, I was unable to manually focus closeup anywhere | |
// close to the extent that it would do on its own when in 'continuous' focus mode. I don't | |
// know why or how common this is, but I know at least the Microsoft LifeCam allows manual | |
// focus through its entire range. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment