newprogrammer
newprogrammer

Reputation: 2604

Using a loaded image in a webgl texture

I want to upload a texture to webgl, and most tutorials do something like this:

var textureImage = new Image();
textureImage.src = "img/texture.png";
textureImage.onload = function() { ...texture loading code... };

So the texture doesn't actually get uploaded to webgl until later, after the image has loaded.

However, I have an image on the DOM that I want to use as a texture, and this image will for sure be loaded because my JavaScript doesn't run until all of the page's content has fully loaded.

How do I get that image on the DOM and upload it to webgl immediately? Instead of waiting for a callback.

Upvotes: 1

Views: 1143

Answers (1)

Aracthor
Aracthor

Reputation: 5907

It's not because your page has fully loaded that your images are loaded too. They are not necessary on your page.

Even if that is the case, you can use onload callback without problem: it will be called as soon as you start the image loading if it is already loaded.

If your try to bind a texture that is not fully loaded, your surface will use instead a complete white texture (or black, in some cases). So you should see the difference yourself.

By the way: to prevent a load before your callback set, it is preferable to set your callback function before your source:

var textureImage = new Image();
textureImage.onload = function() { ...texture loading code... }; // First the callback...
textureImage.src = "img/texture.png"; // Then the source.

Upvotes: 1

Related Questions