Created
November 21, 2024 10:48
-
-
Save engalar/f4b8f3575261f215a3623aa1e95572db to your computer and use it in GitHub Desktop.
mediaDevices test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>拍照示例</title> | |
<style> | |
video, canvas { | |
display: block; | |
margin: 10px auto; | |
} | |
button { | |
display: block; | |
margin: 10px auto; | |
padding: 10px 20px; | |
font-size: 16px; | |
} | |
</style> | |
</head> | |
<body> | |
<h1 style="text-align: center;">拍照示例</h1> | |
<video id="video" autoplay playsinline></video> | |
<button id="capture">拍照</button> | |
<canvas id="canvas"></canvas> | |
<script> | |
const video = document.getElementById('video'); | |
const canvas = document.getElementById('canvas'); | |
const captureButton = document.getElementById('capture'); | |
const ctx = canvas.getContext('2d'); | |
// 获取用户媒体流并显示到 video 元素 | |
async function startCamera() { | |
try { | |
const stream = await navigator.mediaDevices.getUserMedia({ video: true }); | |
video.srcObject = stream; | |
} catch (error) { | |
console.error('无法访问摄像头:', error); | |
alert('无法访问摄像头,请检查权限设置。'); | |
} | |
} | |
// 拍照功能 | |
captureButton.addEventListener('click', () => { | |
canvas.width = video.videoWidth; | |
canvas.height = video.videoHeight; | |
ctx.drawImage(video, 0, 0, canvas.width, canvas.height); | |
}); | |
// 启动摄像头 | |
startCamera(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment