实时更新a-sky src时的问题

issue when real time updating a-sky src

我有一个简单的基于 python 的 websocket 服务器,它将视频帧作为 base64 字符串传递给客户端。

我的客户端代码

var ws = new WebSocket("ws://127.0.0.1:5678/")
ws.onmessage = function (event) {
  console.log("Event received: ", event.data.length)
  let data = event.data.slice(0, -1);
  document.getElementById('sky').setAttribute('src', "data:image/jpg;base64," + data);
};


当我使用

//html
<img id="sky" src="" >

作为图像容器,制作了一个“视频”。

但是当我切换到

<a-scene>
  <a-assets>
    <img id="sky" src="sky.png">
  </a-assets>
  <a-sky src="#sky"></a-sky>
</a-scene>

图片容器卡在第一帧,虽然更新了img元素的src属性,但是网页上的图片并没有改变。

我查看了文档但没有找到任何内容。我应该注意什么?

您应该访问 <a-sky> 的 material 和纹理并设置 needsUpdate 标志。 例如在自定义组件中:

AFRAME.registerComponent('foo', {
  init: function() {
    // wait until the object is loaded
    this.el.addEventListener("loaded", e => {
       // grab the mesh
       var mesh = this.el.getObject3D("mesh")
       // expose the material
       this.material = mesh.material
    })
  },
  tick: function() {
    // when the material is exposed - set the update flag on each tick
    if (!this.material) return;
    this.material.map.needsUpdate = true
  }
}

Canvas 纹理示例 here.


或者您可以通过访问 material 组件来使用更直接的方法:

// Providing the a-sky entity is loaded and ready
a_sky.components.material.material.map.needsUpdate = true

// Untangling it from the left to right:
// entity -> component list -> material component ->
// THREE.js Material object -> texture -> needsUpdate flag