【问题标题】:THREE.js: get data from THREE.WebGLRenderTargetTHREE.js:从 THREE.WebGLRenderTarget 获取数据
【发布时间】:2021-07-22 21:51:39
【问题描述】:

THREE.Texture 可以用作材质中的贴图,并具有称为“图像”的属性。 THREE.WebGLRenderTarget 可以用作材质中的贴图,但没有称为“图像”的属性。

如何从WebGLRenderTarget 检索纹理数据?我想将它保存到一个文件中(或者,如果这不可能,作为一个字节数组)。

【问题讨论】:

    标签: three.js render-to-texture


    【解决方案1】:

    现在的新功能:

    WebGLRenderer.readRenderTargetPixels ( renderTarget, x, y, width, height, buffer )
    

    从 renderTarget 读取像素数据到你传入的缓冲区。缓冲区应该是一个 Javascript Uint8Array,用 new Uint8Array(renderTargetWidth * renderTargetWidth * 4) 实例化,以说明大小和颜色信息。这是 gl.readPixels 的包装器。

    【讨论】:

      【解决方案2】:

      我自己没有尝试过,但是应该可以使用 WebGL 的 readPixels 函数传递渲染目标的(私有)__webglTexture 属性来获取字节数组。

      【讨论】:

      • 谢谢。我会试试的。目前我几乎拥有了我想要使用的东西:renderer.domElement.toDataURL("image/png");但是一些与透明像素接壤的抗锯齿像素预乘了黑色。我会看看我们的建议是否不会受到影响。
      【解决方案3】:

      THREE.WebGLRenderTarget转2D画布的代码片段:

      // allocate RGBA array
      
      let pixels = new Uint8Array(_floor_width * _floor_height * 4);
      
      let can = document.createElement("canvas"), ctx, ctxData, color;
      
      // _floor_target is instance of THREE.WebGLRenderTarget of dimension _floor_width x _floor_height and _renderer is THREE.WebGLRenderer
      
      _renderer.readRenderTargetPixels(_floor_target, 0, 0, _floor_width, _floor_height, pixels);
      
      can.width = _floor_width;
      can.height = _floor_height;
      
      ctx = can.getContext('2d');
      ctxData = ctx.getImageData(0, 0, can.width, can.height);
      
      for (var fy = 0; fy < _floor_height; fy++) {
          for (var fx = 0; fx < _floor_width; fx++) {
      
              // retrieve exact rendered pixel
      
              color = [
                  pixels[fy * _floor_width * 4 + fx * 4 + 0],
                  pixels[fy * _floor_width * 4 + fx * 4 + 1],
                  pixels[fy * _floor_width * 4 + fx * 4 + 2],
                  pixels[fy * _floor_width * 4 + fx * 4 + 3]
              ];
      
              // put pixel to canvas image data (this whole thing might be done much faster)
      
              ctxData.data[(fy * can.width * 4) + (fx * 4) + 0] = color[0];
              ctxData.data[(fy * can.width * 4) + (fx * 4) + 1] = color[1];
              ctxData.data[(fy * can.width * 4) + (fx * 4) + 2] = color[2];
              ctxData.data[(fy * can.width * 4) + (fx * 4) + 3] = color[3];
              
          }
      }
      
      // update canvas image data
      
      ctx.putImageData(ctxData, 0, 0);
      
      document.body.appendChild(can);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-23
        • 2014-07-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-11
        • 2011-02-24
        相关资源
        最近更新 更多