简体   繁体   English

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

[英]Using a loaded image in a webgl texture

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? 如何在DOM上获取该图像并将其立即上传到webgl? Instead of waiting for a callback. 而不是等待回调。

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM