Gathering detailed insights and metrics for jslib-html5-camera-photo
Gathering detailed insights and metrics for jslib-html5-camera-photo
Gathering detailed insights and metrics for jslib-html5-camera-photo
Gathering detailed insights and metrics for jslib-html5-camera-photo
npm install jslib-html5-camera-photo
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
133 Stars
151 Commits
43 Forks
4 Watching
21 Branches
1 Contributors
Updated on 26 Nov 2024
Minified
Minified + Gzipped
JavaScript (93.06%)
HTML (6.66%)
CSS (0.28%)
Cumulative downloads
Total Downloads
Last day
-2%
3,630
Compared to previous day
Last week
7.4%
20,616
Compared to previous week
Last month
5.1%
85,213
Compared to previous month
Last year
9.3%
1,185,628
Compared to previous year
48
The first objective of this package comes from the need to have a js library that can help me to capture picture from mobile or desktop camera through the browser with the HTML5 video and canvas elements. So instead of using the native navigator.mediaDevices.getUserMedia()
and manage the stream
and the constraints
, i need an abstraction it into a small lib that can switch between camera and get the desired resolution.
Another js camera ? Yes! I found webcamjs and jpeg_camera but i need to switch easily from camera environment
and user
. You need to build the constraint for getUserMedia()... Another need is to have a sizeFactor
instead of a fixing 'width' and 'height' that can not fit with the ratio of the resolution that camera can pick.
facing mode
or deviceId
camera, fall back to the default camera.ideal resolution
, fall back to the default resolution.maximum resolution
of the camera, fall back to the default resolution.image format
type between jpg
or png
.jpg
, choose the compression value
is the between [0, 1].image mirror
if you want to get an mirror dataURI of the camera.https://mabelanger.github.io/jslib-html5-camera-photo/
https://caniuse.com/#search=getUserMedia ...(as April 2018)
FACING_MODES [] | Description |
---|---|
USER | The source is facing toward the user (a self-view camera). |
ENVIRONMENT | The source is facing away from the user (viewing the environment). |
src : https://www.w3.org/TR/mediacapture-streams/#dom-videofacingmodeenum
You can use the library with vanilla JavaScript, React, Jquery, Angular...
1npm install --save jslib-html5-camera-photo
1yarn add jslib-html5-camera-photo
1import CameraPhoto, { FACING_MODES, IMAGE_TYPES } from 'jslib-html5-camera-photo'; 2 3// get your video element with his corresponding id from the html 4let videoElement = document.getElementById('videoId'); 5 6// pass the video element to the constructor. 7let cameraPhoto = new CameraPhoto(videoElement);
1cameraPhoto.startCamera(cameraDevice, resolution)
parameters | Description |
---|---|
cameraDevice | Is the string of the camera facingMode or deviceId |
resolution | Is the object resolution ex:. { width: 640, height: 480 } |
If you do not specify any prefer resolution and facing mode, the default is used. The function return a promise. If the promises success it will give you the stream if you want to use it. If it fail, it will give you the error.
1// default camera and resolution 2cameraPhoto.startCamera() 3 .then((stream)=>{/* ... */}) 4 .catch((error)=>{/* ... */});
1// environment (camera point to environment) 2cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {}) 3 .then((stream)=>{/* ... */}) 4 .catch((error)=>{/* ... */}); 5 6// OR user (camera point to the user) 7cameraPhoto.startCamera(FACING_MODES.USER, {}) 8 .then((stream)=>{/* ... */}) 9 .catch((error)=>{/* ... */});
Instead of facing mode, you can specify the deviceId (camera) that you want to use. To know the device id you can get a list of them using see Enumerate the available cameras, so you can start the camera with the deviceId
instead of facing mode, e.g.
1// OR specify the deviceId (use a specific camera) 2const deviceId = 'the_string_of_device_id'; 3cameraPhoto.startCamera(deviceId, {}) 4 .then((stream)=>{/* ... */}) 5 .catch((error)=>{/* ... */});
1// example of ideal resolution 640 x 480 2cameraPhoto.startCamera(facingMode, {width: 640, height: 480}) 3 .then((stream)=>{/* ... */}) 4 .catch((error)=>{/* ... */});
It will try the range of width [3840, 2560, 1920, 1280, 1080, 1024, 900, 800, 640, default]
px to take the maximum width of 3840
px if it can't, 2560
px and so on ... until the fall back of the default value of the camera. The facingMode is optional.
1// It will try the best to get the maximum resolution with the specified facingMode 2cameraPhoto.startCameraMaxResolution(cameraDevice) 3 .then((stream)=>{/* ... */}) 4 .catch((error)=>{/* ... */});
Function that return the dataUri
of the current frame of the camera.
To use that function build the configuration object with the corresponding properties. To use the default value, just ommit the parameter:
sizeFactor (Number): Used to get a desired resolution. Example, a sizeFactor of 1
get the same resolution of the camera while sizeFactor of 0.5
get the half resolution of the camera. The sizeFactor can be between range of ]0, 1]
and the default value is 1
.
imageType (String): Used to get the desired image type between jpg
or png
. to specify the imageType use the constant IMAGE_TYPES, for example to specify jpg format use IMAGE_TYPES.JPG. The default imageType is png
.
imageCompression (Number): Used to get the desired compression when jpg
is selected. choose a compression between [0, 1]
, 1 is maximum, 0 is minimum. The default value imageCompression is 0.92
.
isImageMirror (Boolean): Used to get an image mirror when is set to true
, the result of the dataUri
is the mirror of the actual camera data. Many software that use camera mirror like hangout etc... Please note if you want to enable this option, for consistency with the camera video, you need to use css transform: rotateY(180deg)
to the <video> tag to mirror the stream, because the stream is not mirrored. It's only apply to the canvas dataUri. The default value is false
(no mirror).
IMAGE_TYPES [] | Description |
---|---|
JPG | set image image/jpeg to the data URI |
PNG | set image image/png to the data URI (the default value) |
1// Use all the default value 2const config = {}; 3let dataUri = cameraPhoto.getDataUri(config); 4 5// OR 6 7// Specify sizeFactor, imageType, imageCompression, isImageMirror 8const config = { 9 sizeFactor : 1; 10 imageType : IMAGE_TYPES.JPG 11 imageCompression : .95; 12 isImageMirror : false; 13} 14 15let dataUri = cameraPhoto.getDataUri(config);
the function return null if no stream exist (camera not started) or an object with the camera settings attributes of (aspectRatio, frameRate, height, width).
1let cameraSettigs = cameraPhoto.getCameraSettings(); 2if (cameraSettigs) { 3 let {aspectRatio, frameRate, height, width} = cameraSettigs; 4 let settingsStr = 5 `aspectRatio:${aspectRatio} ` + 6 `frameRate: ${frameRate} ` + 7 `height: ${height} ` + 8 `width: ${width}`; 9 console.log(settingsStr); 10}
enumerateCameras()
Return a Promise that receives an array of MediaDeviceInfo ie:. {kind, label, deviceId}
when the promise is fulfilled. Each object in the array describes one of the available camera (only device-types for which permission has been granted are "available"). The order is significant - the default capture devices will be listed first. If the camera is open, it will only return the promise. If the camera is close, it make sure that camera is granted before returning the promise ie:. do a start/stop cycle of the camera that goes on for 20 ms.
1cameraPhoto.enumerateCameras() 2 .then((cameras)=>{ 3 cameras.forEach((camera) => { 4 let {kind, label, deviceId} = camera; 5 let cameraStr = ` 6 kind: ${kind} 7 label: ${label} 8 deviceId: ${deviceId} 9 `; 10 console.log(cameraStr) 11 }); 12})
You can download photo of the dataUri that you took and pass it to downloadPhoto()
function.
1import { downloadPhoto } from 'jslib-html5-camera-photo'; 2 3let dataUri = cameraPhoto.getDataUri(config); 4downloadPhoto(dataUri, prefixFileName, number); 5// The filename will be saved as the format : 6`${prefixFileName}-${number}.jpg|png}`
the parameters of the downloadPhoto()
function
parameters | Description |
---|---|
dataUri | Is dataUri of the photo |
prefixFileName | Is the string prefix of the fileName |
number | Is the integer number prefix of the fileName with 0 padding |
Function that stop the camera. If it success, no value is returned. It can fail if they is no camera to stop because the camera has already been stopped or never started. It will give a parameter of Error('no stream to stop!')
. Note that each time we start the camera, it internally using this stop function to be able to apply new constraints.
1// It stop the camera 2cameraPhoto.stopCamera() 3 .then(()=>{/* ... */}) 4 .catch((error)=>{/* ... */});
1<!-- needed to by the camera stream --> 2<video id="videoId" autoplay="true"></video> 3 4<!-- needed if you want to display the image when you take a photo --> 5<img alt="imgId" id="imgId"> 6 7<!--buttons to trigger the actions --> 8<button id="takePhotoButtonId">takePhoto</button> 9<button id="stopCameraButtonId">stopCamera</button>
1import CameraPhoto, { FACING_MODES } from 'jslib-html5-camera-photo'; 2 3// get video and image elements from the html 4let videoElement = document.getElementById('videoId'); 5let imgElement = document.getElementById('imgId'); 6 7// get buttons elements from the html 8let takePhotoButtonElement = document.getElementById('takePhotoButtonId'); 9let stopCameraButtonElement = document.getElementById('stopCameraButtonId'); 10 11// instantiate CameraPhoto with the videoElement 12let cameraPhoto = new CameraPhoto(videoElement); 13 14/* 15 * Start the camera with ideal environment facingMode 16 * if the environment facingMode is not available, it will fallback 17 * to the default camera available. 18 */ 19cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT) 20 .then(() => { 21 console.log('Camera started !'); 22 }) 23 .catch((error) => { 24 console.error('Camera not started!', error); 25 }); 26 27// function called by the buttons. 28function takePhoto () { 29 const config = {}; 30 let dataUri = cameraPhoto.getDataUri(config); 31 imgElement.src = dataUri; 32} 33 34function stopCamera () { 35 cameraPhoto.stopCamera() 36 .then(() => { 37 console.log('Camera stoped!'); 38 }) 39 .catch((error) => { 40 console.log('No camera to stop!:', error); 41 }); 42} 43 44// bind the buttons to the right functions. 45takePhotoButtonElement.onclick = takePhoto; 46stopCameraButtonElement.onclick = stopCamera;
A project with react is build with this library react-html5-camera-photo
1import React from 'react'; 2import CameraPhoto, { FACING_MODES } from 'jslib-html5-camera-photo'; 3 4class App extends React.Component { 5 constructor (props, context) { 6 super(props, context); 7 this.cameraPhoto = null; 8 this.videoRef = React.createRef(); 9 this.state = { 10 dataUri: '' 11 } 12 } 13 14 componentDidMount () { 15 // We need to instantiate CameraPhoto inside componentDidMount because we 16 // need the refs.video to get the videoElement so the component has to be 17 // mounted. 18 this.cameraPhoto = new CameraPhoto(this.videoRef.current); 19 } 20 21 startCamera (idealFacingMode, idealResolution) { 22 this.cameraPhoto.startCamera(idealFacingMode, idealResolution) 23 .then(() => { 24 console.log('camera is started !'); 25 }) 26 .catch((error) => { 27 console.error('Camera not started!', error); 28 }); 29 } 30 31 startCameraMaxResolution (idealFacingMode) { 32 this.cameraPhoto.startCameraMaxResolution(idealFacingMode) 33 .then(() => { 34 console.log('camera is started !'); 35 }) 36 .catch((error) => { 37 console.error('Camera not started!', error); 38 }); 39 } 40 41 takePhoto () { 42 const config = { 43 sizeFactor: 1 44 }; 45 46 let dataUri = this.cameraPhoto.getDataUri(config); 47 this.setState({ dataUri }); 48 } 49 50 stopCamera () { 51 this.cameraPhoto.stopCamera() 52 .then(() => { 53 console.log('Camera stoped!'); 54 }) 55 .catch((error) => { 56 console.log('No camera to stop!:', error); 57 }); 58 } 59 60 render () { 61 return ( 62 <div> 63 <button onClick={ () => { 64 let facingMode = FACING_MODES.ENVIRONMENT; 65 let idealResolution = { width: 640, height: 480 }; 66 this.startCamera(facingMode, idealResolution); 67 }}> Start environment facingMode resolution ideal 640 by 480 </button> 68 69 <button onClick={ () => { 70 let facingMode = FACING_MODES.USER; 71 this.startCamera(facingMode, {}); 72 }}> Start user facingMode resolution default </button> 73 74 <button onClick={ () => { 75 let facingMode = FACING_MODES.USER; 76 this.startCameraMaxResolution(facingMode); 77 }}> Start user facingMode resolution maximum </button> 78 79 <button onClick={ () => { 80 this.takePhoto(); 81 }}> Take photo </button> 82 83 <button onClick={ () => { 84 this.stopCamera(); 85 }}> Stop </button> 86 87 <video 88 ref={this.videoRef} 89 autoPlay="true" 90 /> 91 <img 92 alt="imgCamera" 93 src={this.state.dataUri} 94 /> 95 </div> 96 ); 97 } 98} 99 100export default App;
You can build the dist and then serve it with :
1$ npm run buildBrowser 2$ npm run serve:dist
Or you can copy the dist folder of the repo.
Example :
1<script src="/jslib-html5-camera-photo.min.js"></script> 2<script> 3 ... 4 var FACING_MODES = JslibHtml5CameraPhoto.FACING_MODES; 5 var cameraPhoto = new JslibHtml5CameraPhoto.default(videoElement); 6 ... 7</script
I choose the env dev of create-react-app even if it is vanilla js library because it's simple to use and really efficient to develop but you don't necessarily need react to use it. If you want to fix bug or add functionalities please contribute :)
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/16 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
130 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More