html + js 写一个打开电脑本地摄像头的代码 并且实现拍照 和录像的功能
时间: 2024-10-14 18:04:29 浏览: 22
HTML和JavaScript结合可以利用浏览器的WebRTC技术来实现简单的网页摄像头功能。下面是一个基础的示例,展示了如何获取用户摄像头并显示视频流:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webcam Demo</title>
</head>
<body>
<video id="camera" width="640" height="480" autoplay></video>
<button onclick="startCamera()">Start Camera</button>
<button onclick="stopCamera()">Stop Camera</button>
<button onclick="takePhoto()">Take Photo</button>
<button onclick="startRecording()">Start Recording</button>
<button onclick="stopRecording()">Stop Recording</button>
<script>
// 获取摄像头访问权限
function getUserMediaSuccess(stream) {
var camera = document.getElementById('camera');
camera.srcObject = stream;
}
function getUserMediaError(error) {
console.error("Error accessing your webcam: " + error);
}
function startCamera() {
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(getUserMediaSuccess)
.catch(getUserMediaError);
}
}
function stopCamera() {
if (document.getElementById('camera').srcObject) {
document.getElementById('camera').srcObject.getTracks().forEach(track => track.stop());
}
}
function takePhoto() {
if (window.HTMLCanvasElement && window.URL) { // 检查是否支持 canvas toBlob
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = camera.videoWidth;
canvas.height = camera.videoHeight;
ctx.drawImage(camera, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL();
// 这里你可以下载图片,或者做其他处理
console.log('Photo taken:', dataURL);
}
}
function startRecording() {
// 开始录制,这里通常需要服务器支持,因为直接在客户端保存视频文件可能有安全和隐私问题
if (!navigator.mediaDevices.getUserMedia) return;
var options = { audio: true, video: true };
navigator.mediaDevices.getUserMedia(options)
.then(stream => {
const recorder = new MediaRecorder(stream);
recorder.start(); // 开始录制
recorder.ondataavailable = function(event) {
if (event.data.size > 0) {
const url = URL.createObjectURL(event.data); // 创建临时blob url
// 这里你可以创建一个file对象或上传到服务器
console.log('Recording started:', url);
}
};
recorder.onstop = function() {
const blob = new Blob([event.data], { type: 'video/webm' });
// 这里停止录音,并处理blob
console.log('Recording stopped.');
};
})
.catch(err => console.error('Failed to record:', err));
}
function stopRecording() {
if (recorder) {
recorder.stop();
}
}
</script>
</body>
</html>
```
请注意,这个例子中的录像功能受限于浏览器本身和其安全性设置,实际生产环境中可能需要后端服务配合才能存储完整的录像。
阅读全文