-
Thanks to toji and greggman, i find way to load texture from canvas/image. https://webgpufundamentals.org/webgpu/lessons/webgpu-importing-textures.html But I can't find a way to download pictures from canvas or gputexture, so I'll try to ask, what's the best way to download pictures? export async function downloadImageFromCanvas(
device: GPUDevice,
canvas: HTMLCanvasElement // must be webgpu context
): Promise<void> {
} export async function downloadImageFromTexture(
device: GPUDevice,
texture: GPUTexture,
): Promise<void> {
} I asked chatgpt and got some code, but the effect was not good in the test. The downloaded file was invalid, and the canvas screen was broken to white color.
export async function downloadImageFromTexture(
device: GPUDevice,
texture: GPUTexture,
): Promise<void> {
// Create a buffer to store the texture data
const textureExtent = texture.size;
const bufferSize = textureExtent.width * textureExtent.height * 4; // Assuming RGBA format
const buffer = device.createBuffer({
size: bufferSize,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});
// Create a command encoder to copy texture to the buffer
const encoder = device.createCommandEncoder();
const textureView = texture.createView();
encoder.copyTextureToBuffer(
{ texture: texture },
{ buffer: buffer, offset: 0, bytesPerRow: textureExtent.width * 4 },
textureExtent
);
// Submit the command to the GPU
device.queue.submit([encoder.finish()]);
// Map the buffer to read the data
await buffer.mapAsync(GPUMapMode.READ);
const arrayBuffer = buffer.getMappedRange();
// Create an ImageData object from the buffer (RGBA format)
const imageData = new ImageData(
new Uint8ClampedArray(arrayBuffer),
textureExtent.width,
textureExtent.height
);
// You can now use imageData, for example, to display it on a canvas or save it
console.log('Image data downloaded:', imageData);
// Unmap the buffer after use
buffer.unmap();
const url = URL.createObjectURL(imageData);
const link = document.createElement("a");
link.href = url;
link.download = "webgpu_capture.png";
link.click();
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
If you draw to a canvas then you can use example: https://jsgist.org/?src=b217695c8f1104370ba2a81e5efc1ef3 It's not clear what your example code is trying to do and it's rather around about. Calling The 2nd example copies to a buffer and then an ImageData and then tries to make file URL from the ImageData. I don't think it's valid to pass |
Beta Was this translation helpful? Give feedback.
There a no built in way to copy "any" texture ot a blob. You have to do it yourself.
The most efficent way to take any texture to a PNG for some defintion of any would be
use copyTextureToTexture to copy from that texture to a canvas texture then canvas toBlob.
You can only do this if both texture are the canvas texture are the same format
use a compute shader to copy from that texture to a canvas texture then cavnas toBlob