js调用摄像头拍照和录制视频
时间: 2023-02-08 09:45:18 浏览: 140
JavaScript 可以通过访问浏览器的 `MediaDevices.getUserMedia()` API 来访问用户的摄像头并拍照或录制视频。
拍照的示例代码如下:
```
// 获取摄像头视频
navigator.mediaDevices.getUserMedia({video: true})
.then(stream => {
// 将视频流渲染到 video 标签上
video.srcObject = stream;
video.onloadedmetadata = function(e) {
video.play();
};
// 给拍照按钮绑定事件
takePhotoButton.onclick = function() {
// 创建 canvas
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
// 获取 canvas 的 DataURL
const dataURL = canvas.toDataURL('image/jpeg');
// 将 DataURL 设置到 img 标签上显示照片
img.src = dataURL;
};
})
.catch(error => {
console.log("An error occurred: " + error);
});
```
录制视频的示例代码如下:
```
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => {
const mediaRecorder = new MediaRecorder(stream);
//将视频流渲染到 video 标签上
video.srcObject = stream;
video.onloadedmetadata = function (e) {
video.play();
};
//开始录制
recordButton.onclick = function () {
mediaRecorder.start();
recordButton.style.background = "red";
recordButton.innerHTML = "Recording";
}
//结束录制
stopButton.onclick = function () {
mediaRecorder.stop();
recordButton.style.background = "";
recordButton.innerHTML = "Record";
}
//处理视频
mediaRecorder.ondataavailable = function (e) {
chunks.push(e.data);
}
mediaRecorder.onstop = function (e) {
const blob = new Blob(chunks, { type: "video/mp4" });
chunks = [];
阅读全文