代码之家  ›  专栏  ›  技术社区  ›  greedsin

texImage2D:XMLHttpRequest之后的图像无效

  •  1
  • greedsin  · 技术社区  · 7 年前

    我正在使用静态文件服务器加载本地 .jpg -图像。

    let xhr = new XMLHttpRequest();
    this.isLoaded = false;
    this.image = new Image();
    xhr.open("GET", "http://localhost:8080/testing/ressources/" + url, true);
    xhr.responseType = 'blob';
    
    this.textureBuffer = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, this.textureBuffer);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 0, 0, 255]));
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    xhr.onload = (e) => {
    
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        let blob = new Blob([xhr.response], {
          type: 'image/jpg'
        });
        let urlCreator = window.URL || window.webkitURL;
        this.image.src = urlCreator.createObjectURL(blob);
    
        gl.bindTexture(gl.TEXTURE_2D, this.textureBuffer);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.image);
        if (Texture.isPowerOf2(this.image.width) && Texture.isPowerOf2(this.image.height)) {
          gl.generateMipmap(gl.TEXTURE_2D);
        } else {
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        }
        this.isLoaded = true;
      }
    };
    xhr.send();
    

    然而,在呼叫时 gl.texImage2D(...)

    WebGL: INVALID_VALUE: texImage2D: no image
    

    XMLHttpRequest Blob . 也许最好使用 base64 ?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Kirill Dmitrenko    7 年前

    分配url(或)后,图像不同步可用 URL src 所有物你应该等待 load 事件:

    /* ... */
    this.image.onload = () => {
        gl.bindTexture(gl.TEXTURE_2D, this.textureBuffer);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.image);
        /* ... */
    }
    this.image.src = urlCreator.createObjectURL(blob);
    /* ... */