Monaca Docs
Search…
How to Use a Web API
This tutorial explains how to use the MediaDevices API to capture pictures using the device camera in a sample application.

Electron TODO app

Creating the app

First of all, let's create the application with a Monaca template. From the Monaca dashboard, go to Create New Project → Sample Applications. Then choose Electron TODO App from the template list, fill in the Project Name and Description and click Create Project.

Application features

This sample application allows users to create and manage a to do list. The user can add pictures by uploading an existing picture or taking a picture. The list is saved in the local storage.
This tutorial focuses on explaining how we use the MediaCapture API to take pictures using the built-in camera.
Once you open the application, it displays the items saved in the local storage.
Application dashboard
To create a new item, click the + new button on the top right corner of the screen. A new modal dialog will open. You can input a description to the text field and upload an existing picture with the
🖼
button or take a new picture by clicking the
📷
button.
Add a new item
Once the
📷
button is clicked, another modal dialog with the camera view opens. If you press capture, it will capture a photo and save it.
Taking a picture using the laptop camera

HTML explanation

Camera modal

The following code snippet is the camera modal. This modal opens when the camera button is clicked. It has 3 buttons - rotate, capture , and cancel. The rotate button is only visible if the device supports flipping between the front and rear cameras. The video-container element is used to stream pictures from the built-in camera.
1
<div class="modal fade" id="camera-modal" tabindex="-1" data-backdrop="static" role="dialog" aria-labelledby="camera-modal-label" aria-hidden="true">
2
<div class="modal-dialog modal-dialog-centered" role="document">
3
<div class="modal-content">
4
<div class="camera-header-modal"></div>
5
<div class="camera-modal-body modal-body text-center">
6
<video id="video-container" class="camera-preview" autoplay></video>
7
</div>
8
<a id="cordova-camera-cancel" class="btn enabled camera-close-btn" data-dismiss="modal"><i class="fa fa-times"></i> cancel</a>
9
<a id="rotate-camera" class="btn enabled camera-rotate-btn"><i class="fa fa-sync"></i> Rotate</a>
10
<a id="camera-capture" class="btn enabled camera-capture-btn" data-dismiss="modal"><i class="fa fa-camera"></i> Capture</a>
11
</div>
12
</div>
13
</div>
Copied!

JavaScript explanation

Global variable declaration

Let's go quickly through some of the most important variables used in the camera feature:
  • isFrontCamera is used to toggle between front and rear camera.
  • FRONT_CAMERA is used to store the front camera value of the mediaDevices API’s facingModeEnum.
  • REAR_CAMERA is used to store the rear camera value of the mediaDevices API’s facingModeEnum.
1
let isFrontCamera;
2
const FRONT_CAMERA = 'user';
3
const REAR_CAMERA = 'environment';
4
const videoContainer = document.getElementById('video-container');
5
const btnOpenCameraModal = document.getElementById('open-camera-modal');
6
const btnRotateCamera = document.getElementById('rotate-camera');
7
...
Copied!

Checking if the mediaDevices API is supported

The following code snippet is to check whether the mediaDevices API is supported and to display the rotate button if the device is Android and use the rear camera as default.
1
function initialize() {
2
// Check if getUserMedia is supported on the device
3
if (!hasMediaDevicesApi()) {
4
btnOpenCameraModal.hidden = true;
5
}
6
if (isAndroidOS()) {
7
// use rear camera for android
8
btnRotateCamera.hidden = false;
9
isFrontCamera = false;
10
} else {
11
// use front camera for browser/electron
12
btnRotateCamera.hidden = true;
13
isFrontCamera = true;
14
}
15
...
16
}
17
18
function hasMediaDevicesApi() {
19
return !!(navigator.mediaDevices &&
20
navigator.mediaDevices.getUserMedia);
21
}
Copied!

Turning the camera on/off

We will use the function getUserMedia() to ask the user for the permission to use the media input that forms the MediaStream. The stream can contain video (such as camera, video recording device, screen sharing service, etc), audio, or other media. For more details, please refer to the official document. The syntax is as following:
1
var promise = navigator.mediaDevices.getUserMedia(constraints);
Copied!
The function returns a promise and accepts a MediaStreamConstraints object as a parameter.
In the following code snippet, we specify the width and height of the video element to be exactly 250 pixels and set the camera facing mode based on the provided argument. Once the camera device is connected, the Media Stream object is returned and assigned to the video element.
1
function turnOnCamera(frontCamera) {
2
const facingModeOption = frontCamera ? FRONT_CAMERA : REAR_CAMERA;
3
const constraints = {
4
video: {
5
width: {
6
exact: 250
7
},
8
height: {
9
exact: 250
10
},
11
facingMode: facingModeOption
12
}
13
};
14
// Access to the camera and turn it own
15
navigator.mediaDevices.getUserMedia(constraints)
16
.then(handleSuccess)
17
.catch(handleError);
18
19
function handleSuccess(stream) {
20
videoContainer.srcObject = stream;
21
}
22
23
function handleError(error) {
24
alert('Could not get user media API' + JSON.stringify(error));
25
}
26
}
Copied!
To turn off the camera, we need to stop all the sources associated with the video stream.
1
function turnOfCamera() {
2
if (videoContainer && videoContainer.srcObject) {
3
videoContainer.srcObject.getTracks().forEach(function(track) {
4
track.stop();
5
});
6
videoContainer.srcObject = null;
7
}
8
}
Copied!
The function below flips the camera between the front and rear view.
1
function rotateCamera(e) {
2
isFrontCamera = !isFrontCamera;
3
turnOfCamera();
4
turnOnCamera(isFrontCamera);
5
}
Copied!

Capturing a photo

To capture a photo of the video stream, we first create a canvas element whose width and height are the same as the video element. Then, we stop the stream and convert the last capture of it to image format.
1
function takePicture(e) {
2
const canvas = document.createElement('canvas');
3
// Saving current image
4
canvas.width = videoContainer.videoWidth;
5
canvas.height = videoContainer.videoHeight;
6
canvas.getContext('2d').drawImage(videoContainer, 0, 0);
7
// If the video source Object is set, stop all tracks
8
if (videoContainer.srcObject) {
9
videoContainer.srcObject.getTracks().forEach(function(track) {
10
track.stop();
11
try {
12
// Other browsers will fall back to image/png
13
todoItemImage.src = canvas.toDataURL('image/webp');
14
} catch (error) {
15
alert('Could not get the picture.' + JSON.stringify(error));
16
}
17
});
18
}
19
}
Copied!
See Also: