カメラの映像を表示する

2023年5月7日

スマホのカメラ映像をブラウザで表示するだけのサンプルです。

ソース

<div id="p1722">
	<div class="h-flex">
		<div><button class="btn js-start">開始</button></div>
		<div><button class="btn js-stop">停止</button></div>
		<div><button class="btn js-change">切替</button></div></div>
	<div>
	<div class="js-camera">
		<video width="640" height="480" id="video" autoplay="autoplay"></video>
	</div>
</div>
.h-flex {
	width: 100%;
	display: flex;
	flex-direction: row;
}

.btn {
	padding: 1rem 2rem;
	margin-right: 2rem;
}

.js-camera {
	margin-top: 1rem;
	background-color: #000;
	color: #FFF;
}
jQuery(($) => {
	$('#p1722 .js-start').click(videoStart);
	$('#p1722 .js-stop').click(videoStop);
	$('#p1722 .js-change').click(videoChangeCamera);

	let cur = null;

	let setting = {
		audio: false,
		video: {
			width: 480,
			height: 640,
			facingMode: {exact: 'environment'},
			// facingMode: 'user',
		},
	};

	function videoStart() {
		videoStop();
		if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
			navigator.mediaDevices.getUserMedia(setting).then((stream) => {
				const video = document.getElementById('video');
				cur = stream;
				video.srcObject = stream;
				video.play();
			}).catch((a) => {
				$('.js-camera').html('Cannot use camera: ' + a);
			});
		}
	}

	function videoStop() {
		if (cur !== null) {
			cur.getVideoTracks().forEach((camera) => {
				camera.stop();
			});
			cur = null;
		}
	}

	function videoChangeCamera() {
		if (setting.video.facingMode == 'user') {
			setting.video.facingMode = {exact: 'environment'};
		} else {
			setting.video.facingMode = 'user';
		}
		if (cur !== null) {
			videoStop();
			videoStart();
		}
	}

});

javascript,カメラ

Posted by plkl