by Andy Selvig
23. October 2010 23:49
I was playing around with WebGL last night, doing some basic demos from the web. As an experienced OpenGL programmer, I was relieved to see how similar the WebGL API is (with some Javascript-specific tuning, of course).
I set about playing around with the excellent tutorials at http://learningwebgl.com. They step through some basic scenes up to some relatively advanced usage.
However, when playing around with the texture tutorial (http://learningwebgl.com/blog/?p=507), it occurred to me that using an existing HTML element like a canvas tag as a texture would be a common use case for this technology. Unfortunately, WebGL is in its infancy and the amount of documentation availabel through a Google search is limited. After looking around for a while, it wasn't obvious how I would accomplish this seemingly simple task.
After a bit of searching and some playing around with the code, I found (to my delight) that the texImage2D function on a WebGL context can be passed a canvas object for rendering. So, instead of passing it an image element like the tutorial shows, you can simply pass a canvas context:
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvas2d);
where canvas2d is a canvas element that's been grabbed from the DOM with something like document.getElementById("canvas"). This should provide a nice way to create rich, 3D content that is generated from the 2D HTML 5 API.
UPDATE: It seems like, at least in the browser that I've been using for testing (Chromium 8.0 on Ubuntu), you can't use NPOT (non-power of two) elements for the texture. This means that the element must have a width and height that is a power of two.