直接附上代码,请参考 有一定的兼容性问题 ,兼容性的代码我就不附上了哈
提示哈 可以使用try catch
<!DOCTYPE html><html><head><meta charset="utf-8"><title>h5调用电脑摄像头</title><style>.live{height: 400px;width: 400px;margin: 0 auto;}#video{object-fit: fill;}</style></head><body><div class="live"><video id="video" width="400px" height="400px"></video><button id="open">打开摄像头</button></div><script>var video = document.getElementById('video'); function liveVideo(){ navigator.getUserMedia({ video: true }, function(stream){video.srcObject=stream; // 将获取到的视频流对象转换为地址 video.play(); }, function(error){ console.log(error); }); }document.getElementById('open').onclick=function(){liveVideo();}</script></body></html>