Replace color with texture in WebGL

Video games use only color to speed up the download process. Once the textures are ready, they replace the current colors. Is there a way to do this in WebGL? All the tutorials I've seen so far only show how to load color or texture (not one by one).

I assume that the buffer for each shape should be changed after the texture is fully loaded. I would suggest that this is due to an AJAX call, that the texture is available, and then applied using some kind of JavaScript function. Does WebGL have a built-in way to do this without the complicated process of uploading images?

+5
source share
3 answers

, , , , , "" , . , , , "" , .

, , - , , , . , . , , .

, , AJAX :

var image = new Image();
image.addEventListener("load", function() {
    // Image is done loading, push to texture
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
    // Set up any other state needed, such as switching the shader for the mesh
}, true);
image.src = src;

, , , .

+5

, ,

loadTexture(url, initialColor) {

  var tex = gl.createTexture();

  // start with a single color.
  gl.bindTexture(gl.TEXTURE_2D, tex);
  var pixel = new Uint8Array(initialColor);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, pixel);

  // start loading the image
  var img = new Image();
  img.src = url;
  img.onLoad = function() {

    // when the image has loaded update the texture.          
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
    gl.generateMipmap(gl.TEXTURE_2D);
  }
  return tex;
}

// Load a tree texture, use brown until the texture loads.
var treeTexture = loadTexture("tree.png", [255, 200, 0, 255]);
// Load a water texture, use blue until it loads.  
var waterTexture = loadTexture("water.jpg", [0, 0, 255, 255]);

http://webglsamples.googlecode.com, .

, , , , .

. , . , .

+1

In fact, it is very simple, without WebGL, which has any special feature specifically for this, this is what you get for free, just from it is the DOM API. When you upload images, in any case you need to implement the "onload" callback, since loading the image is asynchronous. So just enable the onload callback that needs to be launched to switch from solid color to texture.

0
source

All Articles