arii
arii

Reputation: 143

background img for canvas webgl

Im trying to add img to the background of 3d webgl canvas app but for some reason its not working, what did I miss? I think I have all the required initialize steps.

    initBkgnd();
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.enable(gl.DEPTH_TEST);
    tick();


function tick() {
    requestAnimFrame(tick);
    drawScene();
    initBkgnd();
    animate();
}

function initBkgnd() {
    backTex = gl.createTexture();
    backTex.Img = new Image();
    backTex.Img.onload = function() {
        handleBkTex(backTex);
    }
    backTex.Img.src = "textures/stars.jpg";
}

function handleBkTex(tex) {
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tex.Img);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.bindTexture(gl.TEXTURE_2D, null);
}

Upvotes: 3

Views: 4965

Answers (1)

arii
arii

Reputation: 143

ok, I got it. here is the answer, change:

initBkgnd();
gl.clearColor(0.0, 0.0, 0.0, 1.0); 

to

gl.clearColor(0.0, 0.0, 0.0, 0.0);
initBkgnd();

and add to canvas element sytle:

<canvas id="myCanvas" style="background: url('textures/stars.jpg')" width="1400" height="800"></canvas>

Upvotes: 1

Related Questions