Transparency introduces its own challenges (other than just 'enabling' alpha mode) - you also have to make sure you draw the objects in the correct order.
Cube inside a cube (with the outer cube transparent).
Enabling the alpha mode in the context configuration - also the 'blend' details in the fragment shader (pipeline). Then it's just a matter of setting the alpha information. Instead of setting the alpha for each vertex - we pass an alpha value as a uniform to the fragment shader - then for each cube we can set the alpha value.
Make sure you draw the cubes in the correct order. If you draw the larger cube first - the alpha won't be able to 'mix' with anything behind it - as the little cube hasn't be drawn yet. Also, the big cube will update the depth buffer - so the little cube which sits inside the big cube won't be drawn (it'll be discarded due to the depth).
// Load matrix library on dynamically (on-the-fly) let matprom = await fetch( 'https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.6.0/gl-matrix-min.js' ); let mattex = await matprom.text(); var script = document.createElement('script'); script.type = 'text/javascript'; script.innerHTML = mattex; document.head.appendChild(script);
function buildMatrix( p, r, s ) // position, rotation, scale { // if not set fall back to default values if (!s) s = {x:1, y:1, z:1}; if (!r) r = {x:0, y:0, z:0}; if (!p) p = {x:0, y:0, z:0};
// Create the matrix in Javascript (using matrix library) const modelMatrix = mat4.create();
// create the model transform with a rotation and translation let translateMat = mat4.create(); mat4.fromTranslation( translateMat, Object.values(p) ); let rotateXMat = mat4.create(); mat4.fromXRotation(rotateXMat, r.x); let rotateYMat = mat4.create(); mat4.fromYRotation(rotateYMat, r.y); let rotateZMat = mat4.create(); mat4.fromZRotation(rotateZMat, r.z); let scaleMat = mat4.create(); mat4.fromScaling(scaleMat, Object.values(s) );
// build a model matrix (scale, rotate and position it wherever we want) let modelMatrix = buildMatrix();
// setup the projection let projectionMatrix = mat4.create(); mat4.perspective(projectionMatrix, Math.PI / 2, canvas.width / canvas.height, 0.001, 500.0);
// default camera `lookat` - camera is at -4 units down the z-axis looking at '0,0,0' let viewMatrix = mat4.create(); mat4.lookAt(viewMatrix, [0,0,-3.0], [0,0,0], [0, 1, 0]);
// Draw 2 cubes - on inside the other for (let k=0; k<2; k++) { // update rotation on local cube rotation.x += 0.02; rotation.y += 0.03; rotation.z += 0.01;