-
Notifications
You must be signed in to change notification settings - Fork 0
/
backcam.html
88 lines (75 loc) · 2.41 KB
/
backcam.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>背面カメラ</title>
</head>
<body>
<h1>背面カメラ</h1>
<p>背面カメラの画像を表示します。</p>
<button id="start_button" onclick="startCamera()">Start</button>
<button id="stop_button" onclick="stopCamera()">Stop</button>
<button id="take_photo_button" onclick="takePhoto()">Take Photo</button>
<br />
<!--
<video width="640" height="480" autoplay playsinline style="border: 1px gray solid; width:320px; height: 240px;"></video>
-->
<video width="640" height="960" autoplay playsinline style="border: 1px gray solid; width:320px; height: 480px;"></video>
<br />
<img id="photo" src="" style="border: 1px blue solid; width:320px; height: 480px;">
</body>
<script>
const localVideo = document.querySelector('video');
const photo = document.getElementById('photo');
let localStream = null;
async function startCamera() {
try {
const constraints = {
video: {
//facingMode: "user" // フロントカメラを使用
facingMode: "environment" // 背面カメラを使用
}
};
// カメラの映像を取得
const stream = await navigator.mediaDevices.getUserMedia(constraints);
// <video> エレメントにストリームを設定
localVideo.srcObject = stream;
await localVideo.play();
} catch (error) {
console.error('カメラのアクセスに失敗しました:', error);
}
}
function stopCamera() {
if (localVideo.srcObject) {
localVideo.pause();
localVideo.srcObject.getTracks().forEach(track => {
track.stop();
});
localVideo.srcObject = null;
}
}
function takePhoto() {
const dataURI = getBase64Image(localVideo);
console.log(dataURI);
photo.width = localVideo.videoWidth;
photo.height = localVideo.videoHeight;
photo.src = dataURI;
}
function getBase64Image(video) {
// New Canvas
var canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var ctx = canvas.getContext("2d");
// Draw Image
ctx.drawImage(video, 0, 0);
// To Base64
return canvas.toDataURL("image/jpeg");
// result
// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QB ... +JN3Z6fJ5jtYIskjTqWnRm5WNkb7qHndQB//9k=
}
</script>
</html>