Monday, November 16, 2020

ThreeJS experiments with two scenes on top of another

In this example, there were two scenes, two cameras. 


The main renderer is added using the code below  

document.body.appendChild(renderer.domElement);


The HUD one is not added not as an element but it is rendering on the canvas element as a texture

When the underlying canvas content get changed, the renderer re-draws it 


var hudCanvas = document.createElement('canvas');

var hudBitmap = hudCanvas.getContext('2d');


hudBitmap.beginPath();

hudBitmap.rect(20, 20, 150, 100);

hudBitmap.fillStyle = "red";

hudBitmap.fill();



var cameraHUD = new THREE.OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, 0, 30);


// Create also a custom scene for HUD.

var sceneHUD = new THREE.Scene();


// Create texture from rendered graphics.

var hudTexture = new THREE.Texture(hudCanvas)

hudTexture.needsUpdate = true;


// Create HUD material.

var material = new THREE.MeshBasicMaterial({ map: hudTexture });

material.transparent = true;


// Create plane to render the HUD. This plane fill the whole screen.

var planeGeometry = new THREE.PlaneGeometry(width, height);

var plane = new THREE.Mesh(planeGeometry, material);

sceneHUD.add(plane);




Now we can create a div in the html and ask the renderer to draw with that div. This is done using 


Now created a div like this 


<style>

#container {

background-color: #ff0000;

width: 600px;

height: 600px;

border: 1px solid black;

}

</style>


<div id='container'></div>


And changed the code to be like this below 


var container = document.getElementById('container');


var width = container.offsetWidth;;

var height = container.offsetHeight;


container.appendChild(renderer.domElement);


This was displaying the item in the area given in the div. 


Also the HUD was displayingg the centre as well. 


So the main factor is that if the main scene is moving in animation loop, 

the canvas element to be re-rendered in the  animate loop as well.



Refrecences:

http://localhost/threejs/examples/webgl_sprites2_modified.html

No comments:

Post a Comment