尽管在互联网上有很多实现此目标的示例, 但我们将为你提供涵盖此API的所有需求的重新编译(开始, 暂停, 停止和在android, chrome和firefox上运行的快照)。
以下代码可在Google Chrome浏览器(Android和台式机)和Mozilla Firefox中使用。
<div>
<video id="video" width="500" height="500" autoplay></video>
<!-- You can make the canvas visible if you want -->
<canvas id="canvas" width="500" height="500" style="display:none;"></canvas>
<input type="button" id="takePhoto" value="Photo !"/>
<input type="button" id="pauseTransmission" value="pause transmission"/>
<input type="button" id="resumeTransmission" value="resume transmission"/>
</div>
<script type="text/javascript">
var _streamCopy = null; // If you want to stop the transmission see how this works in Stop Transmision
var button = document.getElementById('takePhoto');
var canvas = document.getElementById('canvas');
var context = canvas.getContext("2d");
var video = document.getElementById('video');
var videoSettings = {
audio:false, video:true
};
var onError = function(err){
console.log(err);
console.log(err.name);
};
// Start the camera when the DOM is ready
window.addEventListener("DOMContentLoaded", function(){
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
_streamCopy = stream;
video.src = stream;
video.play();
}, onError);
} else {
navigator.mozGetUserMedia(videoObj, function(stream){
_streamCopy = stream;
if (video.mozSrcObject !== undefined) {
video.mozSrcObject = stream;
} else {
video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
};
video.play();
}, onError);
}
}, false);
// when the button is clicked, draw the video on the canvas, get a base64 image an open it in a new window.
button.addEventListener('click', function(){
context.drawImage(video, 0, 0, 500, 500);
var image = canvas.toDataURL();
window.open(image);
}, false);
// Pause transmission on click button
document.getElementById('stopTransmission').addEventListener('click', function(){
video.pause();
}, false);
document.getElementById('resumeTransmission').addEventListener('click', function(){
video.play();
}, false);
</script>
注意:请记住, 你需要从http或https连接运行前面的示例, 否则getUserMedia API在file://协议中不可用。
这些都是getUserMedia API中所有可用的错误代码, 请将以下代码的onError事件更改为:
var onError = function(err){
switch(err.name){
case 'PermissionDeniedError':
alert("Permission to use a media device was denied by the user or the system.");
break;
case 'NotFoundError':
alert('No media tracks of the type specified were found that satisfy the constraints specified.');
break;
default:
alert("An unknown error just happened ! :(");
break;
}
};
如果你想彻底停止传输, 我们将使用以下代码:
// _streamCopy is declared in the first example ()
try{
_streamCopy.stop(); // if this method doesn't exist, the catch will be executed.
}catch(e){
_streamCopy.getVideoTracks()[0].stop(); // then stop the first video track of the stream
}
只添加一个按钮和一个事件监听器并执行代码。记住要复制在getUserMedia方法中生成的流变量。
玩得开心 !
评论前必须登录!
注册