在webgl纹理中使用加载的图像

时间:2022-06-13 04:45:03

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

我想将纹理上传到webgl,大多数教程都是这样做的:

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.

因此,在图像加载之后,纹理实际上不会上传到webgl。

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.

但是,我在DOM上有一个我想用作纹理的图像,这个图像肯定会被加载,因为我的JavaScript在所有页面的内容都已完全加载之前不会运行。

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

如何在DOM上获取该图像并立即将其上传到webgl?而不是等待回调。

1 个解决方案

#1


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.

即使是这种情况,也可以毫无问题地使用onload回调:如果已经加载了图像加载,它将立即被调用。

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.

#1


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.

即使是这种情况,也可以毫无问题地使用onload回调:如果已经加载了图像加载,它将立即被调用。

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.