MDN报告了Safari对captureStream
的完全支持。
以下代码从用户的网络摄像头创建流,并将其绑定到视频元素。但是,使用Take picture
按钮捕获静止图像仅在Firefox中有效。
如何使其在Safari中工作?
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="webcam_interface">
<canvas id="canvas" hidden></canvas>
<video id="player" autoplay muted></video>
<br />
<button id="capture">Take picture</button>
<button id="discard">Discard picture</button>
</div>
<script>
const player = document.getElementById("player");
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const captureButton = document.getElementById("capture");
const discardButton = document.getElementById("discard");
const constraints = {
video: true
};
captureButton.addEventListener("click", () => {
// Draw the video frame to the canvas.
context.drawImage(player, 0, 0, canvas.width, canvas.height);
player.srcObject = canvas.captureStream();
});
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
// Copy dimensions of video stream to canvas for still image
const videoTrack = stream.getVideoTracks()[0];
const videoSettings = videoTrack.getSettings();
canvas.height = videoSettings.height;
canvas.width = videoSettings.width;
// Attach the video stream to the video element and autoplay.
player.srcObject = stream;
// Allow the video stream to reappear when discarding image.
discardButton.addEventListener("click", () => {
player.srcObject = stream;
});
});
</script>
</body>
</html>
注意:该代码段不会在此处运行,因为它已被沙箱化:
沙箱访问冲突:在以下位置阻止了帧 “ https://stacksnippets.net”访问位于以下位置的框架 “ https://stackoverflow.com”。请求访问的框架是沙盒 并且缺少“允许相同来源”标志。
因此,要重现此行为,您可能必须使用HTTPS连接访问HTML(在本地打开将不起作用)。