1
votes

I am trying to load an image file into my webGL code and create a texture out of it but while loading the image i get the error:

Uncaught TypeError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': parameter 9 is not of type 'ArrayBufferView'. at Image. (app.js:13)

 var image = new Image();
 image.src = "./js-logo.png";
 image.addEventListener("load", function(){
     gl.bindTexture(gl.TEXTURE_2D, texture);
     gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 10, 10, 0, gl.RGBA, gl.UNSIGNED_BYTE, image);
     gl.generateMipmap(gl.TEXTURE_2D);
 });
1

1 Answers

1
votes

See WebGL Specification - 5.14 The WebGL context:

[...]
void texImage2D(GLenum target, GLint level, GLint internalformat,
                GLsizei width, GLsizei height, GLint border, GLenum format,
                GLenum type, [AllowShared] ArrayBufferView? pixels);
void texImage2D(GLenum target, GLint level, GLint internalformat,
                GLenum format, GLenum type, TexImageSource source); // May throw DOMException

Since image is image is a TexImageSource it has to be

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 10, 10, 0, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

Note, the size of the bitmap is encode int the image object.


Further you should set the texture filtering parameters:

var image = new Image();
image.src = "./js-logo.png";
image.addEventListener("load", function(){
     gl.bindTexture(gl.TEXTURE_2D, texture);
     gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 10, 10, 0, gl.RGBA, gl.UNSIGNED_BYTE, image);
     gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR );
     gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR );
     gl.generateMipmap(gl.TEXTURE_2D);
 });