By leveraging the navigator.mediaDevices.getUserMedia method you can prompt the
user for access to their camera, listen for a click event to grab a photo and
take a snapshot of the user!
First, we set our html:
In the above we’re making a video element,
a button to show that user can click that to take a picture. Finally, we have a
which allows us to draw graphics and animations. In this case, we use this
to render the snapshot we’re going to take.
In the above we make sure the browser the user is on supports the getUserMedia
method and we pass in the params to let the getUserMedia method know we want
video. We then get the user’s media aka access the camera and set the video
element’s property srcObject to the stream coming from the camera and then we
“play” the video meaning we show the output from our camera 👀.
In the above we grab the button element that we created in our HTML and using the
context from our canvas element and use that to draw the image from the video
element that now has an srcObject from what we set above. This is what allows the
drawImage to draw the snapshot we just took.
You could then convert that snapshot to a PNG data URI and even pass that along
to the server for some facial recognition if you wish! Intrigued? Read on for more!
Sorry, this won't work on your device. Trying going to a newer desktop computer!
If you're on an iPhone try opening this page up in native Safari outside of any app (Instagram, Twitter).
Uh oh, looks like you denied us camera access. If you go to the address bar and click
on the camera icon and change the settings to allow this site to access your
camera, you can view the demo after you refresh the page!