HTML 5 Texture from canvas element

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.

 

Tags: , ,

Comments

9/11/2011 7:33:40 AM #

Monalisa A Lina

Nice Information.Thanks.

Monalisa A Lina United States | Reply

9/30/2011 12:29:00 PM #

Michael Davis

Incredibly beneficial appreciate it, It is my opinion your trusty readers might want far more posts similar to this keep up the great hard work.

Michael Davis United States | Reply

10/2/2011 9:50:47 PM #

Johnny Smith

Particularly useful bless you, I presume your subscribers may perhaps want significantly more information similar to this keep up the great work.

Johnny Smith United States | Reply

10/10/2011 6:14:02 AM #

Monalisa Smith

Nice information.....thanks

Monalisa Smith United States | Reply

10/10/2011 12:45:25 PM #

Tim Johnson

Fantastically revealing thanks, There's no doubt that your followers may perhaps want considerably more well written articles along these lines carry on the great work.

Tim Johnson United States | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Page List