Last active
October 15, 2025 22:14
-
-
Save DennisSmolek/4ef2368e9e479993265126207c374e40 to your computer and use it in GitHub Desktop.
Threejs render target utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function renderTargetToImageData( | |
| renderTarget: THREE.WebGLRenderTarget, | |
| renderer: THREE.WebGLRenderer | |
| ): ImageData { | |
| // get the height and width | |
| const height = renderTarget.height; | |
| const width = renderTarget.width; | |
| const buffer = new Uint8Array(width * height * 4); | |
| renderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, buffer); | |
| // flip the buffer | |
| const flippedBuffer = new Uint8Array(buffer.length); | |
| const rowSize = width * 4; | |
| for (let y = 0; y < height; y++) { | |
| const srcRow = (height - 1 - y) * rowSize; | |
| const dstRow = y * rowSize; | |
| flippedBuffer.set(buffer.subarray(srcRow, srcRow + rowSize), dstRow); | |
| } | |
| // Create ImageData with flipped buffer | |
| return new ImageData(new Uint8ClampedArray(flippedBuffer), width, height); | |
| } | |
| export async function renderTargetToBlob( | |
| renderTarget: THREE.WebGLRenderTarget, | |
| renderer: THREE.WebGLRenderer | |
| ): Promise<Blob> { | |
| const imageData = renderTargetToImageData(renderTarget, renderer); | |
| return ImageDataToBlob(imageData); | |
| } | |
| export async function ImageDataToBlob(imageData: ImageData) { | |
| const canvas = document.createElement("canvas"); | |
| const ctx = canvas.getContext("2d"); | |
| if (!ctx) throw new Error("Failed to create canvas context"); | |
| canvas.width = imageData.width; | |
| canvas.height = imageData.height; | |
| ctx.putImageData(imageData, 0, 0); | |
| return new Promise<Blob>((resolve, reject) => { | |
| canvas.toBlob( | |
| blob => { | |
| if (blob) resolve(blob); | |
| else reject(new Error("Failed to create PNG blob from image data")); | |
| }, | |
| "image/png", | |
| 1.0 | |
| ); | |
| }); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment