Camera

This session introduces methods and events to control and interact with the camera of the device enabling users to take pictures. See the example below:

In this example, the camera is turned on and off according to the events show and hide of the modal. Refer to bootstrap documentation for more details about the modal plugin.

Source code
<div class="form-group">
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal-camera">
    <i class="icon-camera"></i> Take a picture
  </button>
</div>

<img id="snapshot-preview" src="unknown.png" class="img-thumbnail">

<div id="modal-camera" class="modal" tabindex="-1" data-backdrop="static">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="icon-camera"></i> Camera
        </h5>
      </div>
      <div class="modal-body">
        <video id="camera" class="camera" data-size="320x240"></video>
      </div>
      <div class="modal-footer">
        <button id="button-snapshot" type="button" class="btn btn-info">Take a picture</button>
        <button type="button" class="btn btn-outline-danger" data-dismiss="modal">Turn off</button>
      </div>
    </div>
  </div>
</div>
$('#modal-camera')
  .on('shown.bs.modal', function () {
    $('#camera').camera('play');
  })
  .on('hidden.bs.modal', function () {
    $('#camera').camera('stop');
  });

$('#button-snapshot').on('click', function () {
  $('#camera').camera('snapshot');
});

$('#camera').on('camera:snapshot', function (e, blob) {
  $('#snapshot-preview').attr('src', blob.dataURL);
  $('#modal-camera').modal('hide');
});
Browser compatibility

IE 11 and below currently does not support getUserMedia. However, there is some polyfills available that you can explore.

Options

Options can be passed via data attributes:

OptionTypeDefaultDescription
data-sizestring320x240The size of the picture. Invalid size will be converted to default size.
Source code

Methods

A few methods are available to control the camera:

MethodDescription
camera('play')Starts the camera. Triggers the event camera:play or camera:error.
camera('stop')Stop the camera. Triggers the event camera:stop.
camera('snapshot')Take a picture from the camera. Triggers the event camera:snapshot.
Source code

Events

Events triggered from the camera can be listened to write custom logic:

EventDescription
camera:playTriggered after the camera starts to play.
camera:errorTriggered if any error occur during the start of the camera.
camera:notSupportedTriggered if the browser does not support camera.
camera:stopTriggered after the camera stop.
camera:snapshotTriggered after a picture is taken. Blob and data URL are ready.
Source code