Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you retrieve WebGL bitmap data?

Tags:

canvas

webgl

It is possible to retrieve the bitmap data HTML Canvas 2D element, is it also possible to access the rendered content of a Canvas 3D / WebGL element as bitmap data?

like image 238
Liam Avatar asked Jan 24 '26 02:01

Liam


2 Answers

The signature of WebGL's readPixels has changed in a later draft.

Instead of returning a new array with the pixel data everytime, you pass an array to fill as last argument :

void readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView pixels)

This allows to reuse the same array for multiple readPixels operations.

like image 95
neonux Avatar answered Jan 25 '26 19:01

neonux


Not as direct as using readPixels, but this might also work. You can also render the canvas to a Image element, like so:

var img = document.getElementById("game-canvas").toDataURL("image/jpeg");
$("#shots").append("<img src=\"" + img + "\" width=\"320\" height=\"480\"/>");

You have to get your webgl context with the special option preserveDrawingContext for this to work though:

var gl = canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});

From there on, if you want to manipulate the image easily, you could render that in a 2d canvas and read the pixels there if you want.

I regularly use this to take "screenshots" of the things I'm playing with.

like image 43
funkaster Avatar answered Jan 25 '26 21:01

funkaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!