<html>
<body>
<!-- 視訊串流顯示位置 -->
<video id="videoElement" class="videoElement" autoplay muted playsinline></video>
<!-- 繪製截圖 -->
<div id="imageContainer"></div>
<!-- 切換鏡頭按鈕 -->
<div>
<button onclick="switchCamera()">切換鏡頭</button>
</div>
</body>
<script>
const videoElement = document.getElementById("videoElement");
// 切換鏡頭
function switchCamera() {
if (videoElement.srcObject) {
let videoTracks = videoElement.srcObject.getVideoTracks();
if (videoTracks.length > 0) {
let currentTrack = videoTracks[0];
let facingMode = currentTrack.getSettings().facingMode;
const constraints = { video: {} };
if (facingMode === "user") {
constraints.video.facingMode = "environment"; // 切換到後鏡頭
} else {
constraints.video.facingMode = "user"; // 切換到前鏡頭
}
// 停止原本的視訊串流
videoTracks.forEach(function (track) {
track.stop();
});
// 確保瀏覽器支援 MediaDevices API
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// 取得新的視訊串流
navigator.mediaDevices
.getUserMedia(constraints)
.then(function (stream) {
videoElement.srcObject = stream;
})
.catch(function (error) {
console.error("無法取得視訊串流:", error);
alert(
"您使用的瀏覽器不支援視訊串流,請使用其他瀏覽器,再重新開啟頁面!"
);
});
} else {
alert(
"您使用的瀏覽器不支援視訊串流,請使用其他瀏覽器,再重新開啟頁面!"
);
}
}
}
}
function startCam() {
// 手機前後鏡頭切換 前鏡頭為 'user',後鏡頭為 'environment'
const constraints = { video: { facingMode: "user" } };
// 確保瀏覽器支援MediaDevices API
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// 取得視訊串流
navigator.mediaDevices
.getUserMedia(constraints)
.then(function (stream) {
// iOS 手機使用時,必須增加的屬性
videoElement.setAttribute("autoplay", "");
videoElement.setAttribute("muted", "");
videoElement.setAttribute("playsinline", "");
videoElement.srcObject = stream;
// 每秒繪製一格畫面
setInterval(function () {
let canvas = document.createElement("canvas");
canvas.width = videoElement.videoWidth;
canvas.height = videoElement.videoHeight;
canvas
.getContext("2d")
.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
// 改變圖片解析度
let scaleFactor = 2; // 調整這個數值以增加解析度
let offscreenCanvas = document.createElement("canvas");
offscreenCanvas.width = canvas.width * scaleFactor;
offscreenCanvas.height = canvas.height * scaleFactor;
let offscreenCtx = offscreenCanvas.getContext("2d");
offscreenCtx.drawImage(
canvas,
0,
0,
offscreenCanvas.width,
offscreenCanvas.height
);
// 直接顯示在前端
// 需要動態建立 <img> 元素,因為手機版可能會無法讀取
let imageElement = document.createElement("img");
// 將 <img> 元素新增到 HTML 中的指定元素上
let containerElement = document.getElementById("imageContainer");
containerElement.innerHTML = "";
imageElement.setAttribute("style", "width:100%");
containerElement.appendChild(imageElement);
imageElement.src = offscreenCanvas.toDataURL("image/jpeg", 1);
}, 1000); // 每秒繪製一次畫面
})
.catch(function (error) {
console.log("無法取得視訊串流:", error);
alert(
"您使用的瀏覽器不支援視訊串流,請使用其他瀏覽器,再重新開啟頁面!"
);
});
} else {
alert("您使用的瀏覽器不支援視訊串流,請使用其他瀏覽器,再重新開啟頁面!");
}
}
// 初始執行函式
startCam();
</script>
</html>