Monaca Docs
  • Monaca
  • Create Your First App
  • Release Notes and Updates
    • Privacy Manifest Requirement for iOS Apps
    • Plugin uses-permission Tag Deduplication Feature
    • iOS Monaca Debugger Discontinuation & Alternative Features
    • Error submitting to iOS App Store (ITMS-90165)
    • Build error in cordova-custom-config
    • Cordova 11 changes
    • Cordova 10 changes
    • Cordova 9 changes
    • New Monaca CLI and Localkit
    • Migration from Cordova to Capacitor
  • Product Guides
    • Monaca Development Overview
    • Monaca Cloud IDE
      • Overview
      • Features in the Monaca Cloud IDE
      • Integrated Terminal
      • Editor Shortcuts
      • Project Dependencies
        • File and Folder Structure
        • JS/CSS Components
        • Cordova Plugins
        • Custom Cordova Plugins
      • Version Control
        • Introduction
        • GitHub Integration
        • Git SSH Integration
      • Monaca CI
        • Overview
        • Deploy Services
        • Deploy to Appetize.io
        • Deploy to DeployGate
        • Deploy to Firebase
      • Build
        • Building for iOS
          • Building an iOS App
          • Build Settings between Monaca and Xcode
        • Building for Android
        • Building for Electron
          • Building on Windows
        • Building for PWA
        • Building for Windows
        • Build Environment Settings
        • Common Build and Application Upload Errors
        • Build History
      • Distribution
        • App Store Distribution
          • App Store Connect Guide
          • iOS App Upload Feature
        • Google Play Distribution
        • Amazon Appstore Distribution
        • Non-market App Distribution
      • Download App Package
      • Tutorial
    • Monaca Localkit
      • Overview
      • Pairing and Debugging
      • Remote Building and Publishing
      • Troubleshooting Guide
      • Tutorial
    • Monaca CLI
      • Overview
      • Monaca CLI Commands
      • Pairing and Debugging
      • Project Dependencies
        • File and Folder Structure
        • JS/JSS Components
        • Cordova Plugins
        • Custom Cordova Plugins
      • Remote Building and Publishing
      • Troubleshooting Guide
      • Tutorial
    • Monaca Debugger
      • Functionalities
      • Installation
        • Monaca Debugger for Android
        • Monaca Debugger for iOS
        • Monaca Debugger for Android Emulator
      • Usage
      • Custom Build Debugger for iOS
      • iOS App Simulator Build
      • Troubleshooting Guide
      • Tutorials
    • Team Dashboard
    • Quick Viewer
    • Migrating from Other Platforms
      • Key Points
      • Cloud IDE preview function settings
      • Migrating from Angular
      • Migrating from Ionic
      • Migrating from React
      • Migrating from Vue
      • Migrating from PhoneGap
        • Key Differences
        • Guide for PhoneGap Build Users
        • Guide for PhoneGap CLI Users
        • Guide for PhoneGap Desktop App Users
      • Migrating from Telerik
  • Build App
    • Build for iOS
      • Creating a Private Key and CSR
      • Creating a Certificate
      • Updating Provisioning Profiles
  • Tutorials
    • Monaca Cloud IDE Tutorial
      • Part 1: Starting a Project
      • Part 2: Running Monaca Debugger with Monaca Cloud IDE
      • Part 3: Building a Monaca App
      • Part 4: Publishing a Monaca App
    • Monaca Localkit Tutorial
      • Part 1: Starting a Project
      • Part 2: Running Monaca Debugger with Monaca Localkit
      • Part 3: Building a Monaca App
      • Part 4: Publishing a Monaca App
    • Monaca CLI Tutorial
      • Part 1: Starting a Project
      • Part 2: Running Monaca Debugger with Monaca CLI
      • Part 3: Building a Monaca App
      • Part 4: Publishing a Monaca App
    • Electron Tutorial
      • How to Use a NPM Package
      • How to Use a Web API
    • Barcode Scanner Plugin
    • Cordova SQLite Storage Plugin
    • Cordova Google Analytics Plugin
    • Cordova Firebase Plugin
    • Cordova In-app Purchase Plugin
    • Cordova AppVersion Plugin
    • Cordova Ionic Keyboard Plugin
    • Cordova Social Sharing Plugin
    • NIFCLOUD mobile backend
    • Phonegap Push Plugin
  • API Reference
    • Monaca API
      • Monaca Cloud & Remote Build API Guide
      • Utilities
    • Core Cordova Plugins
      • Cordova 11.0
        • Battery Status Plugin
        • Camera Plugin
        • Device Plugin
        • Device Motion Plugin
        • Device Orientation Plugin
        • Dialogs Plugin
        • File Plugin
        • Geolocation Plugin
        • InAppBrowser Plugin
        • Media Plugin
        • Media Capture Plugin
        • Network Information Plugin
        • Splashscreen Plugin
        • Vibration Plugin
        • StatusBar Plugin
      • Cordova 10.0
        • Battery Status Plugin
        • Camera Plugin
        • Device Plugin
        • Device Motion Plugin
        • Device Orientation Plugin
        • Dialogs Plugin
        • File Plugin
        • Geolocation Plugin
        • InAppBrowser Plugin
        • Media Plugin
        • Media Capture Plugin
        • Network Information Plugin
        • Splashscreen Plugin
        • Vibration Plugin
        • StatusBar Plugin
        • Whitelist Plugin (Android Only)
      • Cordova 9.0
        • Battery Status Plugin
        • Camera Plugin
        • Contacts Plugin
        • Device Plugin
        • Device Motion Plugin
        • Device Orientation Plugin
        • Dialogs Plugin
        • File Plugin
        • File Transfer Plugin
        • Geolocation Plugin
        • Globalization Plugin
        • InAppBrowser Plugin
        • Media Plugin
        • Media Capture Plugin
        • Network Information Plugin
        • Splashscreen Plugin
        • Vibration Plugin
        • StatusBar Plugin
        • Whitelist Plugin (Android Only)
    • Third-party Cordova Plugins
      • Advanced HTTP Plugin
      • PhoneGap BarcodeScanner Plugin
      • Cordova Custom Config Plugin
      • DatePicker Plugin
      • Share Plugin (Android)
      • WebIntent Plugin (Android)
    • Monaca Power Plugins
      • Monaca HTML5 Resource Encryption
      • Monaca In-App Updater
      • Monaca Secure Storage
      • Barcode Scanner Plugin
      • Android build memory size setting
    • Service Integration
      • Repro
      • AppsFlyer
    • Configuration Files
      • Android
        • Android Configuration
        • config.xml
        • AndroidManifest.xml
      • iOS
        • iOS Configuration
        • config.xml
        • MonacaApp-Info.plist
  • Samples & Tips
    • Sample Apps
      • AdMob
      • Twitter Single Sign-on App
      • Facebook Single Sign-on App
      • Flickr
      • TODO App
      • BirthYear App
      • Break the Bricks
      • Train Catalog App
      • Omikuji Fortune Telling App
      • Clock App
      • Memo Application
      • RSS Reader App
      • Hello World App
    • Tips & Tricks
      • Playing Sound and Music
      • Control the Splash Screen
      • Using Database
  • Features
    • Push Notification
    • SNS Authentication
    • Database
  • FAQ
    • General
    • IDE
    • Build
    • Release
    • Subscription
      • How to Use Activation Code
    • Application
    • Usage
    • Debugger
  • Supported Environments
  • Trouble Shooting
    • Preview Log repeats to reload (Vue packages version mismatch error)
  • Monaca Product Website
  • 日本語
Powered by GitBook
On this page
  • Electron TODO app
  • Creating the app
  • Application features
  • HTML explanation
  • Camera modal
  • JavaScript explanation
  • Global variable declaration
  • Checking if the mediaDevices API is supported
  • Turning the camera on/off
  • Capturing a photo

Was this helpful?

  1. Tutorials
  2. Electron Tutorial

How to Use a Web API

PreviousHow to Use a NPM PackageNextBarcode Scanner Plugin

Last updated 3 years ago

Was this helpful?

This tutorial explains how to use the 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.

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.

<div class="modal fade" id="camera-modal" tabindex="-1" data-backdrop="static" role="dialog" aria-labelledby="camera-modal-label" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="camera-header-modal"></div>
            <div class="camera-modal-body modal-body text-center">
                <video id="video-container" class="camera-preview" autoplay></video>
            </div>
            <a id="cordova-camera-cancel" class="btn enabled camera-close-btn" data-dismiss="modal"><i class="fa fa-times"></i> cancel</a>
            <a id="rotate-camera" class="btn enabled camera-rotate-btn"><i class="fa fa-sync"></i> Rotate</a>
            <a id="camera-capture" class="btn enabled camera-capture-btn" data-dismiss="modal"><i class="fa fa-camera"></i> Capture</a>
        </div>
    </div>
</div>

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.

  • REAR_CAMERA is used to store the rear camera value of the mediaDevices API’s facingModeEnum.

let isFrontCamera;
const FRONT_CAMERA = 'user';
const REAR_CAMERA = 'environment';
const videoContainer = document.getElementById('video-container');
const btnOpenCameraModal = document.getElementById('open-camera-modal');
const btnRotateCamera = document.getElementById('rotate-camera');
...

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.

function initialize() {
  // Check if getUserMedia is supported on the device
  if (!hasMediaDevicesApi()) {
    btnOpenCameraModal.hidden = true;
  }
  if (isAndroidOS()) {
    // use rear camera for android
    btnRotateCamera.hidden = false;
    isFrontCamera = false;
  } else {
    // use front camera for browser/electron
    btnRotateCamera.hidden = true;
    isFrontCamera = true;
  }
  ...
}

function hasMediaDevicesApi() {
  return !!(navigator.mediaDevices &&
    navigator.mediaDevices.getUserMedia);
}

Turning the camera on/off

var promise = navigator.mediaDevices.getUserMedia(constraints);
function turnOnCamera(frontCamera) {
  const facingModeOption = frontCamera ? FRONT_CAMERA : REAR_CAMERA;
  const constraints = {
    video: {
      width: {
        exact: 250
      },
      height: {
        exact: 250
      },
      facingMode: facingModeOption
    }
  };
  // Access to the camera and turn it own
  navigator.mediaDevices.getUserMedia(constraints)
    .then(handleSuccess)
    .catch(handleError);

  function handleSuccess(stream) {
    videoContainer.srcObject = stream;
  }

  function handleError(error) {
    alert('Could not get user media API' + JSON.stringify(error));
  }
}

To turn off the camera, we need to stop all the sources associated with the video stream.

function turnOfCamera() {
  if (videoContainer && videoContainer.srcObject) {
    videoContainer.srcObject.getTracks().forEach(function(track) {
      track.stop();
    });
    videoContainer.srcObject = null;
  }
}

The function below flips the camera between the front and rear view.

function rotateCamera(e) {
  isFrontCamera = !isFrontCamera;
  turnOfCamera();
  turnOnCamera(isFrontCamera);
}

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.

function takePicture(e) {
  const canvas = document.createElement('canvas');
  // Saving current image
  canvas.width = videoContainer.videoWidth;
  canvas.height = videoContainer.videoHeight;
  canvas.getContext('2d').drawImage(videoContainer, 0, 0);
  // If the video source Object is set, stop all tracks
  if (videoContainer.srcObject) {
    videoContainer.srcObject.getTracks().forEach(function(track) {
      track.stop();
      try {
        // Other browsers will fall back to image/png
        todoItemImage.src = canvas.toDataURL('image/webp');
      } catch (error) {
        alert('Could not get the picture.' + JSON.stringify(error));
      }
    });
  }
}

See Also:

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.

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.

FRONT_CAMERA is used to store the front camera value of the mediaDevices API’s

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 . The syntax is as following:

The function returns a and accepts a 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 object is returned and assigned to the video element.

🖼️
📷
📷
facingModeEnum.
official document
promise
MediaStreamConstraints
Media Stream
Building for Electron
MediaDevices API
Application dashboard
Add a new item
Taking a picture using the laptop camera