let isFrontCamera;constFRONT_CAMERA='user';constREAR_CAMERA='environment';constvideoContainer=document.getElementById('video-container');constbtnOpenCameraModal=document.getElementById('open-camera-modal');constbtnRotateCamera=document.getElementById('rotate-camera');...
functioninitialize() {// Check if getUserMedia is supported on the deviceif (!hasMediaDevicesApi()) {btnOpenCameraModal.hidden =true; }if (isAndroidOS()) {// use rear camera for androidbtnRotateCamera.hidden =false; isFrontCamera =false; } else {// use front camera for browser/electronbtnRotateCamera.hidden =true; isFrontCamera =true; }...}functionhasMediaDevicesApi() {return!!(navigator.mediaDevices &&navigator.mediaDevices.getUserMedia);}
次のコードでは、幅と高さを 250 ピクセルに指定し、指定された引数に基づいてカメラに面するモードを設定します。
カメラデバイスが正常に接続されると、 Media Stream オブジェクトが返され、video 要素に割り当てられます。
functionturnOnCamera(frontCamera) {constfacingModeOption= frontCamera ?FRONT_CAMERA:REAR_CAMERA;constconstraints= { video: { width: { exact:250 }, height: { exact:250 }, facingMode: facingModeOption } };// Access to the camera and turn it ownnavigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError);functionhandleSuccess(stream) {videoContainer.srcObject = stream; }functionhandleError(error) {alert('Could not get user media API'+JSON.stringify(error)); }}
functiontakePicture(e) {constcanvas=document.createElement('canvas');// Saving current imagecanvas.width =videoContainer.videoWidth;canvas.height =videoContainer.videoHeight;canvas.getContext('2d').drawImage(videoContainer,0,0);// If the video source Object is set, stop all tracksif (videoContainer.srcObject) {videoContainer.srcObject.getTracks().forEach(function(track) {track.stop();try {// Other browsers will fall back to image/pngtodoItemImage.src =canvas.toDataURL('image/webp'); } catch (error) {alert('Could not get the picture.'+JSON.stringify(error)); } }); }}