three.js - how to render scene.background before a mesh? - javascript

I am a novice to Javascript and ThreeJS. I have a 3D rotating cube that appears on top of a static background, but one frustrating property is that the cube typically appears first and then the background image appears. How do I ensure the background is rendered first? Specifically, I always want the background image to appear before the cube.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="js/three.js"></script>
<script>
function resize() {
var aspect = window.innerWidth / window.innerHeight;
let texAspect = bgWidth / bgHeight;
let relAspect = aspect / texAspect;
bgTexture.repeat = new THREE.Vector2( Math.max(relAspect, 1), Math.max(1/relAspect,1) );
bgTexture.offset = new THREE.Vector2( -Math.max(relAspect-1, 0)/2, -Math.max(1/relAspect-1, 0)/2 );
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = aspect;
camera.updateProjectionMatrix();
}
const scene = new THREE.Scene();
// Arguments:
// 1) Field of Value (degrees)
// 2) Aspect ratio
// 3) Near clipping plane
// 4) Far clipping plane
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
// Need to set size of renderer. For performance, may want to reduce size.
// Can also reduce resolution by passing false as third arg to .setSize
renderer.setSize( window.innerWidth, window.innerHeight );
// Add the rendered to the HTML
document.body.appendChild( renderer.domElement );
// A BoxGeometry is an object that contains all points (vertices) and fill (faces)
// of the cube
const geometry = new THREE.BoxGeometry();
// Determines surface color (maybe texture?)
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
// Mesh takes a geometry and applies the material to it
const cube = new THREE.Mesh( geometry, material );
// Add background image
const loader = new THREE.TextureLoader();
bgTexture = loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' ,
function(texture) {
// Resize image to fit in window
// Code from https://stackoverflow.com/a/48126806/4570472
var img = texture.image;
var bgWidth = img.width;
var bgHeight = img.height;
resize();
});
scene.background = bgTexture;
// By default, whatever we add to the scene will be at coordinates (0, 0, 0)
scene.add( cube );
camera.position.z = 5;
// This somehow creates a loop that causes the rendered to draw the scene
// every time the screen is refreshed (typically 60fps)
function animate() {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
}
animate();
</script>
</body>
</html>

This is happening because the texture is taking longer to load than it takes for Three.js to set up the rest of the scene. You already have a handler for the onLoad callback of TextureLoader.load(), so we can use that to adjust the behavior.
Before scene.add( cube );, add a new line:
cube.visible = false;
Now the cube will still be added to the scene, but it won't be visible. Now after the resize() call at the end of function(texture), add
cube.visible = true;
While testing the problem and solution locally, I ran into a few other, less significant issues with your code. You can see all of the changes I had to make to get it running properly at this Gist.

Related

Canvas dynamic size - height constantly increasing [duplicate]

I have simple three.js scene (canvas) which I want to respond upon window resize event (particularly change in the width of the screen, keeping height constant).
In normal situation i use window.innerWidth, window.innerHeight property to set the size of canvas to match the window size.
However I want to embed three scene in the html.
So I have put three canvas in <div id="three-container">.
In following code when I resize the window (even width only) the height of the canvas keeps growing. Where is the bug? What am I missing?
To get the size of div container I have tried container.clientWidth, container.offsetWidth and $('#three-container').width() (and height respectively), but for all cases the initial height of div is 0 and keeps growing on resize.
Full code listing:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>default</title>
<link rel="icon" href="">
</head>
<body>
<div id='three-container' class= "row"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.js"></script>
<script>
var renderer, scene, camera, cube;
var time = 0.0;
var container = window.document.getElementById( 'three-container' );
var w = 100; //container.clientWidth; // container.offsetWidth
var h = 100; //container.clientHeight; // container.offsetHeight
init();
loop();
function init() {
camera = new THREE.PerspectiveCamera( 45, w / h, 1, 1000 );
scene = new THREE.Scene();
scene.add( camera );
camera.position.z = 16;
renderer = new THREE.WebGLRenderer();
renderer.setClearColor( 0xa696969 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( w, h );
container.appendChild( renderer.domElement );
var geo = new THREE.BoxGeometry( 5, 5, 5);
var mat = new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true } );
cube = new THREE.BoxHelper( new THREE.Mesh( geo, mat ), mat.color );
scene.add( cube );
window.addEventListener( 'resize', function onWindowResize() {
w = container.clientWidth; // container.offsetWidth
h = container.clientHeight; // container.offsetHeight
console.log( " w : " + w + " h : " + h);
renderer.setSize( w, h );
camera.aspect = w / h;
camera.updateProjectionMatrix();
}, false );
}
function loop() {
time += 0.01;
requestAnimationFrame( loop );
cube.rotation.x = time ;
cube.rotation.y = time ;
renderer.render( scene, camera );
}
</script>
</body>
</html>
line-height:0; css-property does the trick and keeps the container's height.
#three-container {
line-height:0;
}
The idea to use this property comes from this SO question
jsfiddle example
It's happening because the container DIV is actually 104px high initially, even though the CANVAS is 100px high. I looked in F12 but couldn't see an obvious reason, such as padding. So you then set the canvas to 104px which makes the div 108px, and so on.
A quick fix is to account for the 4, and this shows you that the above is the problem.
renderer.setSize( w, h - 4 );
I'm afraid though you will need to find a more robust way to find the difference in height.

Three JS with website shows no errors but doesnt work

I am trying to just copy the example three.js page into my own small website with a canvas where the 3d animation should be added to. But it just shows nothing even though it shows no errors.
I tried figuring it out by myself but nothing seems to work :(
i have my canvas element in one div on the page:
var canvas = document.getElementById("background");
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.canvas = canvas;
renderer.setSize(canvas.innerWidth, canvas.innerHeight);
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
var animate = function() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
#background {
height: 100%;
width: 100%;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js"></script>
<canvas id='background'></canvas>
Can you please take a look and show me what i did wrong?
Unless there is a reason for trying to create your own canvas, you can just let three.js produce its own with the following code:
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
With this it creates a new element sets the height and width to match the window and then adds it to the html.
To alter the style further you should use
renderer.domElement.style.attribute = "";
and then you just replace attribute with whatever you are trying to modify.
For more examples you can visit this link:
https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information

Three.js ply colorless (all black)

I am trying to load my ply file using Three.js. It has worked but I almost don't see any colors. There are some glimpses here and there, but it's mostly black (the first image below). The image opens properly (with colors) in MeshLab (the second image below). I have tried vertexColors: THREE.VertexColors (as suggested in Three.js - ply files - why colorless?) and vertexColors: THREE.FaceColors but nothing seemed to help. I am a three.js newbie, so please tell me what am I doing wrong.
and my code:
<!doctype html>
<html lang="en">
<head>
<title>Icon 7</title>
<meta charset="utf-8">
</head>
<body style="margin: 0;">
<script src="js/three.min.js"></script>
<script src="js/PLYLoader.js"></script>
<script src="js/OrbitControls.js"></script>
<script>
// Set up the scene, camera, and renderer as global variables.
var scene, camera, renderer;
init();
animate();
// Sets up the scene.
function init() {
// Create the scene and set the scene size.
scene = new THREE.Scene();
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight;
// Create a renderer and add it to the DOM.
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(WIDTH, HEIGHT);
document.body.appendChild(renderer.domElement);
// Create a camera, zoom it out from the model a bit, and add it to the scene.
camera = new THREE.PerspectiveCamera(35, WIDTH / HEIGHT, 0.1, 100);
camera.position.set(0,0.15,3);
camera.lookAt(new THREE.Vector3(0,0,0));
scene.add(camera);
// Create an event listener that resizes the renderer with the browser window.
window.addEventListener('resize', function() {
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
});
// Set the background color of the scene.
renderer.setClearColor(0xd3d3d3, 1);
// Create a light, set its position, and add it to the scene.
var light = new THREE.PointLight(0xffffff);
light.position.set(0,200,100);
scene.add(light);
// Load in the mesh and add it to the scene.
var loader = new THREE.PLYLoader();
loader.load( './models/foot.ply', function ( geometry ) {
geometry.computeVertexNormals();
geometry.center();
var material = new THREE.MeshStandardMaterial ({ shininess: 1000,vertexColors: THREE.FaceColors } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.x = 0;
mesh.position.y = 0;
mesh.position.z = 0;
mesh.castShadow = false;
mesh.receiveShadow = false;
scene.add( mesh );
} );
// Add OrbitControls so that we can pan around with the mouse.
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.userPanSpeed = 0.05;
}
// Renders the scene and updates the render as needed.
function animate() {
// Read more about requestAnimationFrame at http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimationFrame(animate);
// Render the scene.
renderer.render(scene, camera);
controls.update();
}
</script>
</body>
</html>
Edit: as I don't have separate textures, this is not a duplicate question.
Instead of using MeshStandardMaterial use MeshBasicMaterial

Why am I not able to scale or set position of a mesh in three.js?

As you can see below, I added a mesh to the scene but everytime I try to scale it or set position, I get an error that the mesh is null.
mesh2.position.set(0,0,-5);
mesh2.scale.set(0.2, 0.3, 0.2);
Uncaught TypeError: Cannot read property 'position' of null
check it out at testing2.site44.com
Please help as I have wasted hours trying to get this to work.
function init()
{
var scene = new THREE.Scene();//CREATE NEW THREE JS SCENE
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var renderer = new THREE.WebGLRenderer({antialias:true}); //INIT NEW THREE JS RENDERER
renderer.setPixelRatio( window.devicePixelRatio ); //SET PIXEL RATIO FOR MOBILE DEVICES
renderer.setClearColor(new THREE.Color('#005b96'), 1) //SET BG COLOR
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); // SET SIZE
document.body.appendChild( renderer.domElement ); //APPLY CANVAS TO BODY
renderer.domElement.id = "canvas_threeJS";//ADD ID TO CANVAS
//ADD CAMERA TO THE SCENE
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR =1000;
var camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
camera.position.set(0,3,8); //SET CAMERA POSITION
camera.lookAt(new THREE.Vector3(0,0,-5));
scene.add(camera);
//ADD AMBIENT LIGHT
var ambientLight = new THREE.AmbientLight("#6497b1");
scene.add(ambientLight);
//HANDLE WINDOW RESIZE
//ADD MAIN LIGHT
var light = new THREE.PointLight("#b3cde0",.6);
light.position.set(-5,13,-1);
scene.add(light);
var mesh2 = null;
var loader = new THREE.JSONLoader();
loader.load('assets/models/spaceship001.json', function(geometry) {
mesh2 = new THREE.Mesh(geometry);
scene.add(mesh2);
console.log("done loading model");
});
mesh2.position.set(0,0,-5);
// mesh2.scale.set(0.2, 0.3, 0.2);
//START POSITION OF A LEVEL GROUP
var levelSpawn = -100;
//GET VISIBLE WIDTH AT levelSpawn POSITION
var vFOV = camera.fov * Math.PI / 180; // convert vertical fov to radians
var height = 2 * Math.tan( vFOV / 2 )*levelSpawn; // visible height
var aspect = window.innerWidth / window.innerHeight;
var width = height * aspect;// visible width
//START RENDER
update();
function update()
{
//UPDATE 3D SCENE
renderer.render( scene, camera );
//KEEP RENDERING
requestAnimationFrame( update );
}
}
The problem is that javascript is an asynchronous language. Depending on your background you should read up on that. Try putting a console.log("setting scale and postion") just under or above those two lines. What you'll notice is that the position and scale is set before the mesh is loaded.
What you need to do is set the position and scale inside the callback function that you pass to the load function, just under the console.log("done loading model"); line.
You can also read up on javascript Promises to understand it better.

three.js: rotate tetrahedron on correct axis

I have to display a rotating tetrahedron in an animated HTML5 graphic, using three.js.
When i create the object, it's upside down, but it should be on the ground with one surface, like on this screenshot: http://www10.pic-upload.de/08.10.12/v3nnz25zo65q.png
This is the code for rotating the object, at the moment. Stored in render() function. But the axis is incorrect and the object is rotating wrong.
object.useQuaternion = true;
var rotateQuaternion_ = new THREE.Quaternion();
rotateQuaternion_.setFromAxisAngle(new THREE.Vector3(0, 1, 1), 0.2 * (Math.PI / 180));
object.quaternion.multiplySelf(rotateQuaternion_);
object.quaternion.normalize();
(copied from Three.JS - how to set rotation axis)
This is the result at the moment: http://jsfiddle.net/DkhT3/
How can i access the correct axis to move/rotate the tetrahedron on the ground?
Thanks for suggestions!
Don't do what you copied. It is not correct.
I am assuming that what you want to do is to start off with a tetrahedron that is right-side-up to begin with. One thing you can do is to modify THREE.TetrahedronGeometry() to use four vertices that produce the tetrahedron that you want.
If you want to use the existing code, then what you have to do is to apply a rotation to the geometry right after it is created, like so:
const geometry = new THREE.TetrahedronGeometry( 10, 0 );
geometry.applyMatrix4( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3( 1, 0, - 1 ).normalize(), Math.atan( Math.sqrt( 2 ) ) ) );
geometry.translate( 0, 10 / 3, 0 ); // optional, so it sits on the x-z plane
(Determining the proper rotation angle requires a bit of math, but it turns out to be the arctangent of the sqrt( 2 ) in this case, in radians.)
three.js r.146
Download three.js from [http://www.html5canvastutorials.com/libraries/Three.js] library and put in the below HTML code.
You will get good output.
<!Doctype html>
<html lang="eng">
<head>
<title>I like shapes</title>
<meta charset="UTF-8">
<style>
canvas{
width: 100%;
height: 100%
}
body{
background: url(mathematics.jpg);
width: 800px;
height: 500px;
}
</style>
</head>
<body>
<script src="three.js"></script>
<script>
// creating a Scene
var scene = new THREE.Scene();
// Adding Perspective Camera
// NOTE: There are 3 cameras: Orthographic, Perspective and Combined.
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
//create WebGL renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//Drawing a Tetrahedron.
var pyramidgeometry = new THREE.CylinderGeometry(0, 0.8, 4, 4, false);
//Change colour of Pyramid using Wireframe
var pyramidmaterial = new THREE.MeshBasicMaterial({wireframe: true, color: 0x0ff000});
var pyramid = new THREE.Mesh(pyramidgeometry, pyramidmaterial); //This creates the cone
pyramid.position.set(3.1,0,0);
scene.add(pyramid);
//moving camera outward of centre to Z-axis, because Cube is being created at the centre
camera.position.z = 5;
//we have a scene, a camera, a cube and a renderer.
/*A render loop essentially makes the renderer draw the scene 60 times per second.
I have used requestAnimationFrame() function.*/
var render = function() {
requestAnimationFrame(render);
/*cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
cube.rotation.z += 0.01;*/
pyramid.rotation.y += 0.01;
pyramid.rotation.x += 0.01;
pyramid.rotation.z += 0.01;
renderer.render(scene, camera);
};
// calling the function
render();
</script>
</body>
</html>

Categories

Resources