Last active
August 31, 2021 00:26
-
-
Save vorg/2543472a7d9b448e0ed7a4c6eea73277 to your computer and use it in GitHub Desktop.
Minimal example of making screenshot of WebGPU canvas
This file contains 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
//Tested on Chrome Canary Version 94.0.4598.0, macOS 11.5 | |
const canvas = document.createElement("canvas"); | |
canvas.width = 512; | |
canvas.height = 512; | |
document.body.appendChild(canvas); | |
const clearColor = { | |
r: Math.random(), | |
g: Math.random(), | |
b: Math.random(), | |
a: 1.0, | |
}; | |
let renderPassDescriptor = { | |
colorAttachments: [ | |
{ | |
loadValue: clearColor, | |
storeOp: "store", | |
view: null, | |
}, | |
], | |
}; | |
async function init() { | |
const adapter = await window.navigator.gpu.requestAdapter(); | |
const device = await adapter.requestDevice(); | |
const ctx = canvas.getContext("webgpu"); | |
ctx.configure({ | |
device: device, | |
format: "bgra8unorm", | |
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, //if you skipt this you will get transparent png | |
}); | |
const link = document.createElement("a"); | |
let download = true | |
function draw() { | |
const commandEncoder = device.createCommandEncoder(); | |
renderPassDescriptor.colorAttachments[0].view = ctx | |
.getCurrentTexture() | |
.createView(); | |
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); | |
passEncoder.endPass(); | |
device.queue.submit([commandEncoder.finish()]); | |
if (download) { | |
download = false | |
canvas.toBlob( | |
(blob) => { | |
link.download = "Screenshot " + new Date() + ".png"; | |
link.href = URL.createObjectURL(blob); | |
link.dispatchEvent(new MouseEvent("click")); | |
}, | |
"image/png", | |
1 | |
); | |
} | |
requestAnimationFrame(draw); | |
} | |
draw(); | |
} | |
init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
COPY_SRC
should no longer be needed in Chromium (that was a known issue). Could you try without it?