Is an imageData CanvasPixelArray directly available to a canvas WebGL context?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 11:55:58

You can use gl.readPixels:

// Render your scene first then...
var left = 0;
var top = 0;
var width = canvas.width;
var height = canvas.height;
var pixelData = new Uint8Array(width * height * 4);
gl.readPixels(left, top, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixelData);

pixelData now contains the scene's pixel data as unsigned bytes (0-255) laid out as [R, G, B, A, R, G, B, A...] Should be the same data as getImageData but at a much lower cost.

[EDIT:]

I forgot to mention that if you're going to be doing this, you'll want to create your WebGL context with the preserveDrawingBuffer option, like so:

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

This prevents WebGL's inner workings from clearing the buffer before you get to it (which would result in you reading a whole lot of empty pixels). Enabling this option has the potential to slow down your rendering, but it should still be loads faster than 5-8 FPS! :)

 renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer:true });



 var gl = renderer.getContext()
 var buf = new Uint8Array(200 * 200 * 4);
 gl.readPixels(0, 0, 200, 200, gl.RGBA, gl.UNSIGNED_BYTE, buf);


console.log(buf);

this works fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!