首页 > 解决方案 > 如何将网络摄像头源用作 A-Frame 纹理?

问题描述

我想将网络摄像头流作为纹理附加到aframe中的实体,这可能吗?我该怎么做?

我想要的效果的一个例子包括:

标签: webrtcaframe

解决方案


https://media.giphy.com/media/cJjZg8kXSUopNzZP4V/giphy.gif

添加资产

第一步是将视频添加为资产:

<a-assets>
  <video id="webcam" playsinline></video>
</a-assets>

请注意 playinline 指令,它阻止页面进入全屏模式,尤其是在移动设备上。这只是我想添加的一个小细节,因为尽管我们的应用程序将全屏运行,但我希望应用程序决定这一点,而不是一些随机的视频元素!

创建流

接下来,我们使用以下命令创建流:

<!-- Start the webcam stream and attach it to the video element -->
<script>
  // You can also set which camera to use (front/back/etc)
  navigator.mediaDevices.getUserMedia({audio: false, video: true})
  .then(stream => {
    let $video = document.querySelector('video')
    $video.srcObject = stream
    $video.onloadedmetadata = () => {
      $video.play()
    }
  })
</script>

应用纹理

最后,我们将流作为材料应用到任何实体上:material="src: #webcam"

工作演示

<script src="https://aframe.io/releases/0.8.2/aframe.min.js"></script>

<!-- Create an empty video tag to hold our webcam stream -->
<a-assets>
  <video id="webcam" playsinline></video>
</a-assets>

<!-- Creates -->
<a-scene background="color: #ECECEC">
  <a-box position="-1 0.5 -3" rotation="0 45 0" shadow material="src: #webcam"></a-box>
  <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E" shadow></a-sphere>
  <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D" shadow></a-cylinder>
  <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" shadow></a-plane>
</a-scene>

<!-- Start the webcam stream and attach it to the video element -->
<script>
  // You can also set which camera to use (front/back/etc)
  // @SEE https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
  navigator.mediaDevices.getUserMedia({audio: false, video: true})
  .then(stream => {
    let $video = document.querySelector('video')
    $video.srcObject = stream
    $video.onloadedmetadata = () => {
      $video.play()
    }
  })
</script>

如果 Code Runner 不起作用,您也可以在此处使用它:https ://glitch.com/~webcam-as-aframe-texture


推荐阅读