So, I wanted to make a simple button that would let users snap a picture. I figured it’d be a cool little feature for this app I’m tinkering with. Nothing fancy, just a button, tap it, opens the camera, take a picture, and that’s it.
Getting Started
First things first, I needed a button. I’m using plain HTML and JavaScript for this project, so I just whipped up a basic button element:
And yeah I gave an id which named “captureButton” so I could grab it easily with JavaScript later.
Wiring it Up
Next, I added a little bit of JavaScript to the mix. I needed to listen for when someone clicks that button. Simple enough:
I got the button using its ID, and then I used addEventListener to watch for a ‘click’. When it’s clicked, it’ll run my function.
Accessing the Camera
Okay, here’s where it got a little tricky. Accessing the user’s camera isn’t as straightforward as, say, changing the button’s color. Browsers are pretty strict about this for security * gotta use something called the MediaDevices API, and specifically, the getUserMedia() method.
I tried a bunch of different approaches, and after some trial and error (and lots of Googling), I got something that kind of worked.
See, getUserMedia() wants a “constraints” object. Basically, you tell it what kind of media you want – audio, video, or both. I just wanted video, so I set that to true.
Handling the Stream
The getUserMedia() method is asynchronous, meaning it doesn’t give you the camera feed right away. It returns something called a “Promise”. And it worked! The browser asked me for permission to use the camera. Progress!
This Promise resolves with a MediaStream object, which is like a live feed from the camera. I needed to do something with that stream. The easiest thing is to display it in a video element.
Displaying the Camera Feed
I added a video element to my HTML.
Then, back in my JavaScript, inside that then() block, I took the MediaStream and set it as the source of my video element:
And there it was! A live feed from my webcam, right there on my webpage.
Taking the Picture
But the last step, I need a function to take a picture, so the user can click the button and snap a picture. so I need to create a canvas at first.
Then, I used the drawImage() method of the canvas to essentially take a snapshot of what was currently being displayed in the video element.
Finally, got the image, so all done!