本文介绍了可以从 WebGL 纹理对象轻松创建 HTML 图像元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用我渲染的 WebGLTexture 对象并使用它来创建 HTML 图像元素.目标是为了调试目的显示离屏渲染过程的结果.应该比将纹理渲染到全屏四边形(我目前的调试方法)容易得多.

I'd like to take a WebGLTexture object that I've rendered into and use it to create an HTML image element. The goal is to display the result of an offscreen rendering pass for debugging purposes. It should be a lot easier than rendering the texture to a full screen quad, my current debugging method.

在 WebGL 中从图像元素创建纹理非常简单:

Creating a texture from an image element is really easy in WebGL:

var image = new Image();
image.src = "myImg.jpg";

// image loads...

var texture = gl.createTexture();
gl.bindTexture(texture);
gl.texImage2D(_gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, image);

图像加载和解码完全由您负责.

Image loading and decoding is completely taken care of for you.

有没有类似的简单方法来做相反的事情?即:

Is there a similarly easy way to do the reverse? i.e.:

// This doesn't work
var img = new Image(texture);

// But maybe this could
var img = createImageFromTexture(texture);

function createImageFromTexture(texture) {
    // ... some combination of tricks ...
}

如果有办法做到这一点,我相信它在调试之外的环境中很有用.我会继续看看我是否能找到一种方法来做到这一点,但我觉得之前有人必须尝试过.

If there is a way to do this, I'm sure it will be useful in contexts outside of debugging. I'll continue to see if I can find a way to do it, but I feel like someone has had to have attempted this before.

推荐答案

您可以创建一个由纹理支持的framebuffer,然后使用 gl.readPixels() 从帧缓冲区中读取原始像素数据.获得数据像素后,您可以使用 ImageData 将它们复制到 2D 画布.然后,您可以通过将图像的 src 属性设置为 canvas.toDataURL() 来构建图像.

You can create a framebuffer backed by a texture and then read the raw pixel data out of the framebuffer using gl.readPixels(). Once you have the data pixel, you can copy them to a 2D canvas using ImageData. Then you can construct an Image by setting the image's src property to canvas.toDataURL().

function createImageFromTexture(gl, texture, width, height) {
    // Create a framebuffer backed by the texture
    var framebuffer = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);

    // Read the contents of the framebuffer
    var data = new Uint8Array(width * height * 4);
    gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);

    gl.deleteFramebuffer(framebuffer);

    // Create a 2D canvas to store the result
    var canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    var context = canvas.getContext('2d');

    // Copy the pixels to a 2D canvas
    var imageData = context.createImageData(width, height);
    imageData.data.set(data);
    context.putImageData(imageData, 0, 0);

    var img = new Image();
    img.src = canvas.toDataURL();
    return img;
}

这篇关于可以从 WebGL 纹理对象轻松创建 HTML 图像元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:31