Take a Selfie With JavaScript | premiumwd
Development / Tips & Tricks

Take a Selfie With JavaScript

by danny markov on July 25, 2016

In this tutorial we are going to show you how to take a selfie with JavaScript. Using a photobooth app that takes images using the camera on your phone, laptop or desktop. We will showcase a number of awesome native APIs that allowed us to make our project without any external dependencies, third-party libraries or Flash – vanilla JavaScript only!

Note that this app uses experimental technologies that are not available in desktop and mobile Safari.

1. The App

To the end user our app is just an oversimplified version of the camera app you can find on any smartphone. It uses a hardware camera to take pictures – that’s it. Under the hood, however, a whole lot of JavaScript magic is going on. Here is a high-level overview:

  1. We access the camera input and get a video stream from it using the getUserMedia API.
  2. Project the camera stream onto a HTML video element.
  3. When the user wants to take a picture, we copy the current video frame and draw it on a canvas element.
  4. Transform the canvas into an image dataURL which then can be shown on the screen or downloaded as a PNG.

In the article below we will only look at the more interesting parts of the code. For the full source go to the Download button near the top of this page or checkout the demo on JSfiddle.

Keep in mind that the

navigator.getUserMedia

API is considered deprecated, but it still has pretty good browser support and is the only way to access the camera right now, until it’s future replacement – navigator.mediaDevices.getUserMedia gains wider browser support.

2. Accessing The Camera

JavaScript provides a native API for accessing any camera hardware in the form of the navigator.getUserMedia method. Since it handles private data this API work only in secure HTTPS connections and always asks for user permission before proceeding.

Permission Dialog In Desktop Chrome

If the user allows to enable his camera,

navigator.getUserMedia

gives us a video stream in a success callback. This stream consists of the raw broadcast data coming in from the camera and needs to be transformed into an actual usable media source with the

createObjectURL

method.

navigator.getUserMedia(
    // Options
    {
        video: true
    },
    // Success Callback
    function(stream){

        // Create an object URL for the video stream and
        // set it as src of our HTLM video element.
        video.src = window.URL.createObjectURL(stream);

        // Play the video element to show the stream to the user.
        video.play();
 
    },
    // Error Callback
    function(err){

        // Most common errors are PermissionDenied and DevicesNotFound.
        console.error(err);

    }
);

3. Taking a Still Photo

Once we have the video stream going, we can take snapshots from the camera input. This is done with a nifty trick that utilizes the mighty

<canvas>

element to grab a frame from the running video stream and save it in an

<img>

element.

function takeSnapshot(){

    var hidden_canvas = document.querySelector('canvas'),
        video = document.querySelector('video.camera_stream'),
        image = document.querySelector('img.photo'),

        // Get the exact size of the video element.
        width = video.videoWidth,
        height = video.videoHeight,

        // Context object for working with the canvas.
        context = hidden_canvas.getContext('2d');


    // Set the canvas to the same dimensions as the video.
    hidden_canvas.width = width;
    hidden_canvas.height = height;

    // Draw a copy of the current frame from the video on the canvas.
    context.drawImage(video, 0, 0, width, height);

    // Get an image dataURL from the canvas.
    var imageDataURL = hidden_canvas.toDataURL('image/png');

    // Set the dataURL as source of an image element, showing the captured photo.
    image.setAttribute('src', imageDataURL); 

}

The canvas element itself doesn’t even need to be visible in the DOM. We are only using its JavaScript API as a way to capture a still moment from the video.

4. Downloading The Photo

Of course, we not only want to take glorious selfies but we also want be able to save them for future generations to see. The easiest way to do this is with the download attribute for

<a>

elements. In the HTML the button looks like this:

<a id="dl-btn" href="#" download="glorious_selfie.png">Save Photo</a>

The

download

attribute transforms our anchor from a hyperlink into a download button. Its value represents the default name of the downloadable file, the actual file to download is stored in the

href

attribute, which as you can see is empty for now. To load our newly taken photo here, we can use the image dataURL from the previous section:

function takeSnapshot(){

    //...

    // Get an image dataURL from the canvas.
    var imageDataURL = hidden_canvas.toDataURL('image/png');

    // Set the href attribute of the download button.
    document.querySelector('#dl-btn').href = imageDataURL;
}

Now when somebody clicks on that button they will be prompted to download a file named glorious_selfie.png, containing the photo they took. With this our little experiment is complete!

Conclusion

We hope that you’ve learned a lot from this tutorial and that you now feel inspired to build some kick-ass photo apps. As always, feel free to ask questions or share ideas in the comment section below!

Design tips, tricks, and freebies. Delivered weekly.

Get design tips and tricks, latest news from us and some goodies for signing up.
Email Address...
Give it a try—it only takes a click to unsubscribe

You might also like...

 Development / WordPress

5 Ways to Make Your WooCommerce Store Swift and Faster

Starting an online store with WooCommerce is pretty simple. You just need to select a domain, a hosting plan and…

 Plugins / Tips & Tricks / WordPress

11 Amazing WordPress Plugins for 2017

Instead of writing a regular top ten piece, I decided to focus on WordPress plugins that you probably don’t know about….

 Development / Tips & Tricks / WordPress

4 Effective Ways to Help Grow Your WordPress Blog

 Many bloggers misuse the marketing concept: “If you build it, they will come.” Content may be the primary building block…

No comments

Sorry, the comment form is closed at this time.

Subscribe to Blog

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

See why people are switching to use our products. See Features Get Started
+ +

Get awesome design content

Get design tips and tricks, latest news from us and some goodies for signing up.
Email Address...
Give it a try—it only takes a click to unsubscribe
%d bloggers like this: