Looking for a good alternative to WebcamJS? Please check out JpegCamera by Adam Wróbel. It has many advanced features that WebcamJS is lacking (for example, upload multiple photos at once, retry failed uploads, CSRF tokens, make sure camera is ready), and has a very clean and object-oriented design.
Important Note for Chrome 47+
Google Chrome has made it a strict requirement that your website be secure (HTTPS) if you want to access the camera. This change is live in Chrome version 47 and up. So basically, if you want to use WebcamJS, you will need to host your website with SSL / HTTPS. The only alternative is to force Flash fallback mode on Chrome, which is probably not desirable.
See this Chromium page for details: https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
Note that you do not need HTTPS for localhost / 127.0.0.1. Here is the list of rules for Chrome which unlock the camera:
WebcamJS has been tested on the following browsers / operating systems:
|Mac OS X||Chrome 30+||Works -- Chrome 47+ requires HTTPS|
|Mac OS X||Firefox 20+||Works|
|Mac OS X||Safari 6+||Requires Adobe Flash Player|
|Windows||Chrome 30+||Works -- Chrome 47+ requires HTTPS|
|Windows||IE 9||Requires Adobe Flash Player|
|Windows||IE 10||Requires Adobe Flash Player|
|Windows||IE 11||Requires Adobe Flash Player|
Here are some live demos showcasing various features of the library:
|Basic Demo||Demonstrates a basic 320x240 image capture.|
|Large Demo||Demonstrates capturing a large 640x480 image, but showing a live preview at 320x240.|
|Crop Demo||Demonstrates cropping a 240x240 square out of the center of a 320x240 webcam image.|
|Large Crop Demo||Demonstrates a large 480x480 square crop, from a 640x480 image capture, with a 240x240 live preview.|
|HD Demo||Demonstrates a 720p HD (1280x720) image capture (only supported by some webcams).|
|SFX Demo||Demonstrates a camera shutter sound effect at capture time.|
|Flash Demo||Demonstrates forcing Adobe Flash fallback mode.|
|Freeze Demo||Demonstrates freezing / previewing a snapshot before saving it.|
|Mirror Demo||Demonstrates flipping the image horizontally (mirror mode).|
|Full Combo Demo||A full combination demo showcasing all features.|
WebcamJS is open source, MIT licensed, and available on GitHub:
webcam.swf files on your web server (both in the same directory), and drop in this HTML snippet:
This will create a live camera view in the
my_camera DIV, and when the Take Snapshot link is clicked it will take a still snapshot, convert it to a JPEG, and deliver a Data URI which is inserted into the
my_result DIV as a standard
<IMG SRC> tag.
Data URIs may be passed around like any URL, and can be submitted to your server as well (see below for example of this).
If you want to override the default settings, just call
Webcam.set() and pass in a hash with any of the following keys:
|Param Name||Default Value||Notes|
||(Auto)||Width of the live camera viewer in pixels, defaults to the actual size of the DOM element.|
||(Auto)||Height of the live camera viewer in pixels, defaults to the actual size of the DOM element.|
||(Auto)||Width of the captured camera image in pixels, defaults to the live viewer size.|
||(Auto)||Height of the captured camera image in pixels, defaults to the live viewer size.|
||(Disabled)||Width of the final cropped image in pixels, defaults to
||(Disabled)||Height of the final cropped image in pixels, defaults to
||jpeg||Desired image format of captured image, may be "jpeg" or "png".|
||90||For JPEG images, this is the desired quality, from 0 (worst) to 100 (best).|
||true||Enable or disable Flash fallback, if there is no native webcam access.|
||false||Setting this to true will always run in Adobe Flash fallback mode.|
||false||Setting this to true will flip the image horizontally (mirror mode).|
||30||Set the desired fps (frames per second) capture rate.|
||"./webcam.swf"||Set an alternate location for the Adobe Flash fallback SWF file|
||"ERROR: No Adobe Flash Player detected. Webcam.js relies on Flash for browsers that do not support getUserMedia (like yours)."||text/html for flash player not detected.|
||true||Whether to unfreeze the camera after snap (defaults to true)|
||"webcam"||Which HTTP POST parameter name to use when uploading the webcam image file.|
Here is an example of overriding a single parameter. Remember to call this before you attach the viewer.
You can also set multiple parameters at once by passing in an object, like this:
Webcam;// Attach camera here
WebcamJS is initialized and activated by "attaching" a live camera viewer to a DOM element. The DOM element must already be created and empty. Pass in an ID or CSS selector to the
Webcam.attach() function. Example:
This will activate the user's webcam, ask for the appropriate permission, and begin showing a live camera image in the specified DOM element.
Note that the browser itself handles asking the user for permission to use their camera. WebcamJS has no control over this, so there is no way to style the UI. Each browser does it a little differently, typically a bar at the top of the page, and Flash does it inside the view area.
Snapping a Picture
To snap a picture, just call the
Webcam.snap() function, passing in a callback function. The image data will be passed to your function as a Data URI, which you can then display in your web page, or submit to a server. Example:
Your function is also passed a HTML5 Canvas and a 2D Context object, so you can gain access to the raw pixels instead of a compressed image Data URI. These are passed as the 2nd and 3rd arguments to your callback function. Example:
If you would prefer that WebcamJS simply copy the image into your own canvas, it can do that instead of generating a Data URI (which can be an expensive operation). To do this, simply pass your canvas object to the
Webcam.snap() method, as the 2nd argument, right after your callback function. Example:
// assumes 'myCanvas' is a reference to your own canvas object, at the correct sizeWebcam;
Customizing Image Size
WebcamJS will automatically size the live camera viewer based on the DOM element it is attached to. However, you can override this by setting the
Webcam;// Attach camera here
The size of the captured JPEG / PNG image is set to match the live camera viewer by default. However, you can override this by setting the
dest_height. Note that you can set the destination image size different than the viewer size. So you can have a small live viewer, but capture a large image. Example:
Webcam;// Attach camera here
Cropping The Image
WebcamJS can also crop the final image for you, to any dimensions you like. This is useful for when you want a square image (perhaps for a website profile pic), but you want to capture the image from the user's webcam at 4:3 ratio to be fully compatible (some cameras require 4:3 and cannot capture square images). To do this, include
crop_height params, specifying the area to crop out of the center of the final image:
Webcam;// Attach camera here
This would crop a 240x240 square out of the center of the 320x240 webcam image. The crop is also reflected in the live preview area. In this case the live preview would also be cropped to 240x240, so the user can see exactly what portion of the image will be captured.
Flipping The Image (Mirror Mode)
If you want, WebcamJS can "flip" (mirror) both the live preview and captured image horizontally. This will produce a reversed image, as if you were looking in a mirror. To enable this optional feature, include the
flip_horiz param, and set it to
Webcam;// Attach camera here
Freezing / Previewing The Image
Want to provide your users with the ability to "freeze" (i.e. preview) the image before actually saving a snapshot? Just call
Webcam.freeze() to freeze the current camera image. Then call
Webcam.snap() to save the frozen image, or call
Webcam.unfreeze() to cancel and resume the live camera feed.
The idea here is to provide a photo-booth-like experience, where the user can take a snapshot, then choose to keep or discard it, before actually calling
Webcam.snap() to save the image.
Setting an Alternate SWF Location
By default WebcamJS looks for the SWF file in the same directory as the JS file. If you are hosting the SWF in a different location, please set it using the
Webcam.setSWFLocation() function. It should be on the same domain as your page. Example:
Note that this is only used if the user's browser doesn't support HTML5 getUserMedia, and WebcamJS has to fallback to using an Adobe Flash movie to capture the camera.
To shut down the live camera preview and reset the system, call
Webcam.reset(). This removes any DOM elements we added, including a Flash movie if applicable, and resets everything in the library to the initial state. Example:
To use the library again after resetting, you must call
Webcam.attach() and pass it your DOM element.
Here is a list of all the API function calls available in the WebcamJS library.
||Set configuration parameters. Pass a key + value, or a hash with multiple keys/values.|
||Register an event listener for a given event. Pass in the event name, and a callback function.|
||Remove an event listener for a given event. Pass in the event name, and the callback function to remove. Omit the callback reference to remove all listeners.|
||Initialize library and attach live camera to specified DOM object.|
||Shut down library and reset everything. Must call
||Freeze the current live camera frame, allowing the user to preview before saving.|
||Cancel the preview (discard image) and resume the live camera view.|
||Take a snapshot from the camera (or frozen preview image). Pass callback function to receive data.|
||Upload a saved image to your server via binary AJAX. Fires progress events (see below).|
Webcam.on() function, passing an event name and callback function. Here is a table of the available event types:
||Fires when the library finishes loading.|
||Fires when the user's camera goes live (i.e. showing a live preview). This will only happen after the user allows access to their camera.|
||Fires when an error occurs (your callback function is passed an error string).|
||Fires repeatedly while an upload is in progress (see below).|
||Fires once when the upload completes (see below).|
By default the
Please note that WebcamJS allows multiple listeners on the same event. So if you call
Webcam.on() multiple times, your callback functions are all added to an array for the event, and all of them will be called when the event fires. So only call
Webcam.on() once for each listener function. You can use
Webcam.off() to remove listeners from an event.
Submitting Images to a Server
Webcam.upload() function accepts three arguments: the Data URI containing the Base64 encoded image data as returned from
snap(), a URL to your server API endpoint (PHP script, etc.), and a callback function to execute when the upload is complete. You can alternatively specify the callback using
The image data is uploaded as part of a standard multipart form post, and included as a form element named
webcam. To gain access to this data, write some server-side code like this (PHP shown):
// be aware of file / directory permissions on your servermove_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
Treat the uploaded data as if you were receiving a standard form submission with a
<input type="file" name="webcam"> element. The data is sent in the same exact way.
If you need to pass any additional information along with your image to the server, please add a query string to your script URL. For example:
var username = 'jhuckaby';var image_fmt = 'jpeg';var url = 'myscript.php?username=' + username + '&format=' + image_fmt;Webcam;
Those variables will then be available to your server-side code however you would normally access the query string, e.g.
$_GET['username'] in PHP.
Tracking Upload Progress
If you want to track progress while your image is uploading, you can register an event listener for the
uploadProgress event. This event is called very frequently while an upload is in progress, and passes the function a floating point number between 0.0 and 1.0 representing the upload progress. Here is how to use:
Including in an Existing Form
If you are already submitting a form on your page, and simply want to include the image data in your form, you can do this. However, note that the data will be Base64 encoded until it gets to the server, so you will need to decode it on the server-side, and the file size in transit will be about 30% larger than normal.
This alternate upload technique is also shown here because it's probably the only way it'll ever work in IE 7, 8, and 9. Those older IE versions do not support binary AJAX and blobs, so the standard
Webcam.upload() function will not work, and you'll have to use a form trick like this:
First, add a hidden text element to your form:
Then, when you snap your picture, stuff the Data URI into the form field value (minus the header), and submit the form:
Finally, in your server-side script, grab the form data as if it were a plain form text field, decode the Base64, and you have your binary image file! Example here in PHP, which assumes JPEG format:
$encoded_data = $_POST['mydata'];$binary_data = base64_decode( $encoded_data );// save to server (beware of permissions)$result = file_put_contents( 'webcam.jpg', $binary_data );if (!$result) die("Could not save image! Check file permissions.");
Custom User Media Constraints (Advanced)
The HTML5 getUserMedia API has a constraints system by which you can specify optional or mandatory requirements for the video stream. These include things such a minimum or maximum resolution and/or framerate. By default, WebcamJS will specify a mandatory minimum width and height, matching your
dest_height parameters. However, if you want to customize this, you can set a
constraints parameter using
Webcam.set(), and pass in an object containing all the custom constraints you want. Example:
To remove the mandatory constraints and instead just specify the resolution you would prefer, you can set simple
height properties like this:
Please call this this before calling
Note that some browsers may not support every possible constraint, so consult your browser's documentation and test in all your supported browsers before using this advanced feature. For example, as of this writing Chrome 44 doesn't support framerate constraints.
The MIT License (MIT)
Copyright (c) 2012 - 2015 Joseph Huckaby
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.