image.png效果图
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>屏幕共享</title>
</head>
<body>
<div id="container">
<video id="video-local" autoplay playsinline></video>
<button id="showVideo" onclick="startShard()">开始共享屏幕</button>
</div>
</body>
</html>
核心代码:
const constraints = window.constraints = {
audio: true,
video: true
};
async function startShard() {
if(window.stream!=null){
alert('你已开启屏幕共享,请勿重复打开哦');
return false;
}
try {
await navigator.mediaDevices.getDisplayMedia(constraints).then(gotStream);
} catch (err) {
console.error(err)
}
}
function gotStream(stream) {
const videoEle = document.querySelector('video');
window.stream = stream;
videoEle.srcObject = stream;
//监听手动点击“停止分享”
stream.getVideoTracks()[0].onended = ()=>{
//监听以后的处理逻辑……
alert('屏幕共享已关闭')
videoEle.srcObject = null;
}
}
网友评论