THREE.js 中的纹理到数据 URI

to_*_*asz 5 three.js

大多数人都有相反的问题,但我想问是否有任何简单的方法可以将纹理数据返回到数据 URI。

我正在使用渲染到纹理(RTT)来渲染背景中的场景(使用不同的相机)。我希望能够将此数据发送到服务器或仅显示在 img 元素中以进行测试。

to_*_*asz 2

谢谢大家的帮助。我已经想出了一个解决办法。也许它可以做得更简单,但这个解决方案工作并且看起来相当快。

实时传输时间

this.renderer.render(this.scene, camera, this.rttTexture, true);
Run Code Online (Sandbox Code Playgroud)

获取场景数据。

this.pixelsIn = new Uint8Array(4 * 1024 * 1024);
var gl = this.renderer.context;
var framebuffer = this.rttTexture.__webglFramebuffer;
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.viewport(0, 0, 1024, 1024);
gl.readPixels(0, 0, 1024, 1024, gl.RGBA, gl.UNSIGNED_BYTE, this.pixelsIn);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
Run Code Online (Sandbox Code Playgroud)

创建二维上下文。

this.printScreenCanvas = document.createElement("canvas");
this.printScreenCanvas.width = 1024;
this.printScreenCanvas.height = 1024;
this.printScreenContext = this.printScreenCanvas.getContext('2d');
Run Code Online (Sandbox Code Playgroud)

为 2d 上下文创建存储。

this.pixelsOut = this.printScreenContext.createImageData(1024, 1024);
Run Code Online (Sandbox Code Playgroud)

必须转换数据+翻转Y。

var row, col, k = 4*1024;
for(var i=0; i<this.pixelsIn.length; i++) {
    row = Math.floor(i/k);
    col = i % k;
    this.pixelsOut.data[(1023-row)*k+col] = this.pixelsIn[i];
}
Run Code Online (Sandbox Code Playgroud)

将数据存储在二维上下文中。

this.printScreenContext.putImageData(this.pixelsOut,0,0);
Run Code Online (Sandbox Code Playgroud)

获取数据 URI 数据。

return this.printScreenCanvas.toDataURL();
Run Code Online (Sandbox Code Playgroud)