console
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta http-equiv='X-UA-Compatible' content='ie=edge'>
<title>Camera demo</title>
</head>
<body>
<button id='snap'>获取</button>
<button id='stop'>暂停</button>
<button id='record-start'>开始录制</button>
<button id='record-stop'>结束录制</button>
<video id='video'></video>
<canvas id='canvas'></canvas>
<img id="img">
<video id='record-video'></video>
<script>
window.addEventListener('DOMContentLoaded', function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
video = document.getElementById('video'),
img = document.getElementById('img'),
mediaStream = null;
function getUserMedia(constrains, success, error) {
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
} else if (navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia(constrains).then(success).catch(error);
} else if (navigator.mozGetUserMedia) {
navigator.mozGetUserMedia(constrains).then(success).catch(error);
} else if (navigator.getUserMedia) {
navigator.getUserMedia(constrains).then(success).catch(error);
}
}
function success(stream) {
mediaStream = stream;
try {
video.srcObject = stream;
} catch (error) {
var CompatibleURL = window.URL || window.webkitURL;
video.src = CompatibleURL.createObjectURL(stream);
}
video.play();
}
function error(error) {
console.log("访问用户媒体设备失败:", error.name, error.message);
}
if ((navigator.mediaDevices && navigator.mediaDevices.getUserMedia) || navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia) {
getUserMedia({
video: {
width: 480,
height: 320
}
}, success, error);
} else {
alert("你的浏览器不支持访问用户媒体设备");
}
document.getElementById("snap").addEventListener("click", function () {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
context.drawImage(video, 0, 0);
img.src = canvas.toDataURL("image/jpeg");
});
document.getElementById("stop").addEventListener("click", function () {
if (video.paused) {
video.play();
} else {
video.pause();
}
});
let recorder, chunks = [];
document.getElementById("record-start").addEventListener("click", function () {
chunks.length = 0;
recorder = new MediaRecorder(mediaStream);
recorder.ondataavailable = (e) => {
chunks.push(e.data);
}
recorder.start(100);
});
document.getElementById("record-stop").addEventListener("click", function () {
recorder.stop();
let recorderFile = new Blob(chunks, { type: recorder.mimeType });
let recorderVideo = document.getElementById('record-video');
recorderVideo.autoplay = true;
recorderVideo.width = video.videoWidth;
recorderVideo.height = video.videoHeight;
try {
recorderVideo.srcObject = recorderFile;
} catch (error) {
var CompatibleURL = window.URL || window.webkitURL;
recorderVideo.src = CompatibleURL.createObjectURL(recorderFile);
}
});
}, false);
</script>
</body>
</html>