THREE.OBJLoader can not display obj file? - three.js

This is my code ... and I searched a lot about it ... but I couldn't find where is the problem that nothing will show !! also there is not any errors ! I also can send you my files if u can help me ... thank you
<body>
<script src="Three.js"></script>
<script src="DDSLoader.js"></script>
<script src="MTLLoader.js"></script>
<script src="OBJLoader.js"></script>
<script>
// Setup a new scene
var scene = new THREE.Scene();
// Setup the camera
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.z = 0;
camera.position.x = 0;
camera.position.y = 0;
// Setup the renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
var onError = function ( xhr ) { };
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'obj/table/' );
mtlLoader.load( 'table.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'obj/table/' );
objLoader.load( 'table.obj', function ( object ) {
object.position.x = 0;
object.position.y = 0;
object.position.z = 0;
scene.add( object );
}, onProgress, onError );
});
// Render loop to rotate our sphere by a little bit each frame
var render = function () {
renderer.setClearColor( 0xa9db8b );
renderer.render(scene, camera);
};
render();
</script>
<canvas width="1366" height="662" style="width: 1366px; height: 662px;"></canvas>
</body>

As an option: you call render() before your model loaded.
Try this:
objLoader.load( 'table.obj', function ( object ) {
object.position.x = 0;
object.position.y = 0;
object.position.z = 0;
scene.add( object );
render(); // call it in the callback function
}, onProgress, onError );
});

You are placing your object at (0,0,0) and the camera at the same location.
Try this code for your camera:
// Place camera on x-axis
camera.position.set(10,0,0);
camera.up = new THREE.Vector3(0,0,1);
camera.lookAt(new THREE.Vector3(0,0,0));

Related

glb/gltf Model not loading on Netlify, but loads locally

I am using Three.js with the gltf loader to load a single .glb resource onto a page. It works locally, though then I upload to Netlify the model does not load and the xhr progressEvent's total is 0. I checked that the model is still being loaded in the network tab, but yet it still does not show in the page.
It seems this problem has occurred before, but not sure how to resolve it when using Netlify if there are any environment variables I need to change.
https://github.com/mrdoob/three.js/issues/15584
HTML
<div class="model-wrapper">
<div id="model_target" class="loading">
<div class="myimage fade" id="placeholder">
<img src="images/placeholder.png" height="328px"/></div>
</div>
</div>
<!-- THREE.js -->
<script src="https://threejs.org/build/three.js"></script>
<!-- GLTFLoader.js -->
<script src="https://cdn.rawgit.com/mrdoob/three.js/r92/examples/js/loaders/GLTFLoader.js"></script>
JS
```
let camera, scene, renderer;
const mouse = new THREE.Vector2();
const look = new THREE.Vector2();
const windowHalf = new THREE.Vector2( window.innerWidth /
2, window.innerHeight / 2 );
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 0.4),
-9);
var raycaster = new THREE.Raycaster();
var pointOfIntersection = new THREE.Vector3();
let modelLoaded = false;
let placement = document.getElementById("model_target")
window.addEventListener('DOMContentLoaded', init);
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 60, 1, 1, 1000);
camera.position.set(5, 3, 28)
//camera.position.y = 13;
var light = new THREE.DirectionalLight("#fff", 1.5);
var ambient = new THREE.AmbientLight("#FFF");
light.position.set( 0, -70, 100 ).normalize();
scene.add(light);
// scene.add(ambient);
var texture = new THREE.Texture();
var loader = new THREE.GLTFLoader();
THREE.Cache.enabled = true;
// Load a glTF resource
loader.load(
// 3d model resource
'./assets/models/mrktechy3.glb',
// called when the resource is loaded
function ( gltf ) {
mesh = gltf.scene;
mesh.scale.set( 5, 5, 5 );
scene.add( mesh );
},
// called when loading is in progress
function ( xhr ) {
// Loading progress of model
console.log(xhr);
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
if((xhr.loaded / xhr.total * 100) == 100){
modelLoaded = true;
//Loading overlay
var placeholder = document.getElementById("placeholder");
placeholder.classList.add("faded");
placement.classList.remove("loading");
}
},
// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
);
//scene.background = new THREE.Color(0xfff); //Set background color
renderer = new THREE.WebGLRenderer( { alpha: true, antialias: true } );
renderer.setSize( 800, 500 );
placement.appendChild( renderer.domElement );
renderer.setClearColor(0x000000, 0);
renderer.gammaOutput = true;
document.addEventListener( 'mousemove', onMouseMove, false );
window.addEventListener( 'resize', onResize, false );
render()
}
function onMouseMove( event ) {
if (modelLoaded){
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 0;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 0;
raycaster.setFromCamera(mouse, camera);
raycaster.ray.intersectPlane(plane, pointOfIntersection);
mesh.lookAt(pointOfIntersection);
}
}
function onResize( event ) {
const width = 800 ;
const height = 500;
windowHalf.set( width / 2, height / 2 );
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize( width, height );
}
var easeAmount = 8;
function update(){
look.x += (mouse.x-look.x)/easeAmount;
look.y += (mouse.y-look.y)/easeAmount;
raycaster.setFromCamera(look, camera);
raycaster.ray.intersectPlane(plane, pointOfIntersection);
mesh.lookAt(pointOfIntersection);
}
function render() {
camera.aspect = renderer.domElement.clientWidth / renderer.domElement.clientHeight;
camera.updateProjectionMatrix();
requestAnimationFrame( render );
if (modelLoaded){
update();
}
renderer.render( scene, camera );
}
```
Any glb resource can be replaced in the code and it works locally but not when hosted.
In the IIS settings, try to add mime type for gltf. Something like this:
application/gltf-buffer .gltf
This solved my problem.

Can Not See 3d Obj. Model When Loaded With THREE.js

I load an obj file from an external resource with three.js. From onProgress callback function I can see that object is loaded without any error. However I can not see object on the screen.
I tried diffrent textures and different camera postion but still can not see the object.
Interestingly, obj file can be easily seen with Windows Object Vİewer without any settings.
Here the boj file I used and CAD program settings while exporting obj:
Obj files and related files with obj file: https://ufile.io/e3oplk29
Obj File export options on the CAD program: https://pasteboard.co/Ieu9226.jpg
Here the code I use:
////************HERE LIGHT AND SCENE AND CAMERA****************////
var directionalLightIntensity = 1;
var ambientLightIntensity = 0.05;
var ambiColor = "#ffffff";
var metalValue = 0;
var roughValue = 1;
var kumas = "<?php echo CUSTOMSHIRT_PLUGIN_DIR_URL.'customshirt/';?>"+"kumas/kumas9.jpg";
var kumasNormal = "<?php echo CUSTOMSHIRT_PLUGIN_DIR_URL.'customshirt/';?>"+"kumas/kumas9_NORMAL.jpg";
var container = document.getElementById('cloth-container');
if(window.innerWidth > 767 ){
var render_height = document.documentElement.clientHeight - 8;
var render_width = document.documentElement.clientWidth - 130;
}else{
var render_height = document.documentElement.clientHeight - 95;
var render_width = document.documentElement.clientWidth;
}
const scene = new THREE.Scene();
var light = new THREE.DirectionalLight('#ffffff', directionalLightIntensity);
var ambientLight = new THREE.AmbientLight(ambiColor, ambientLightIntensity);
light.position.set(0,0,1);
scene.add(light);
scene.add(ambientLight);
const camera = new THREE.PerspectiveCamera(75, render_width/render_height,0.1,1000);
camera.position.z = 1.8 ;
camera.position.y = 1.2;
camera.position.x = 0;
camera.lookAt( 0,1.2,0);
const renderer = new THREE.WebGLRenderer({ alpha: true , antialias:true });
renderer.setSize(render_width, render_height);
renderer.setClearColor( 0xffffff, 0);
container.appendChild(renderer.domElement);
const objLoader = new THREE.OBJLoader();
const mtlLoader = new THREE.MTLLoader();
mtlLoader.setMaterialOptions({side:THREE.DoubleSide});
////************HERE OBJ LOAD WITH THREE.JS****************////
mtlLoader.load( "<?php echo CUSTOMSHIRT_PLUGIN_DIR_URL.'customshirt/yaka6-n4/';?>"+'yaka6-n4.mtl', function( materials ) {
materials.preload();
objLoader.setMaterials( materials );
objLoader.load( "<?php echo CUSTOMSHIRT_PLUGIN_DIR_URL.'customshirt/yaka6-n4/';?>"+'yaka6-n4.obj', function ( obj ) {
collar_obj = obj;
obj.position.set( obj_pos_x, obj_pos_y, obj_pos_z );
obj.rotation.y = 0;
// texture
texture = textureLoader.load(kumas);
textureNormal= textureLoader.load(kumasNormal);
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
textureNormal.wrapS = textureNormal.wrapT = THREE.RepeatWrapping;
texture.repeat.x = textureXRepeat;
texture.repeat.y = textureYRepeat;
textureNormal.repeat.x = textureXRepeat;
textureNormal.repeat.y = textureYRepeat;
obj.traverse( function ( child ) {
//if ( child.isMesh ) child.material.map = texture;
if ( child.isMesh ) child.material = new THREE.MeshStandardMaterial({
//color: 0x996633,
//specular: 0x050505,
//shininess: my_shine_value,
metalness: metalValue,
roughness: roughValue,
map: texture,
normalMap: textureNormal,
//side: THREE.DoubleSide
});
});
scene.add( obj );
},
// onProgress callback
function ( xhr ) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
// onError callback
function ( err ) {
console.log( 'An error happened' );
});
});
////************HERE RENDERER****************////
function render(){
requestAnimationFrame(render);
renderer.render(scene,camera);
}
render();
Any idea is appreciated.
Thanks
It seems your object's geometry is translated. Since the asset is composed of multiple meshes, I suggest the following code to center your OBJ.
const box = new THREE.Box3().setFromObject( object );
const center = box.getCenter( new THREE.Vector3() );
object.position.x += ( object.position.x - center.x );
object.position.y += ( object.position.y - center.y );
object.position.z += ( object.position.z - center.z );
I've added this code in the onLoad() callback of OBJLoader in the following official example and was able to see the object (a shirt collar).
https://threejs.org/examples/webgl_loader_obj_mtl
three.js R 104

Javascript threejs 3D draw solid cubic with border

I follow threejs example, webgl_interactive_draggablecubes.html. My project is to use Threejs to make a container loading plan. So I want to make solid cubic with a border. something we could see with/without border difference.
,
I could use multi-material, but then my drag and drop is broken. The code snippet in creating Geometry3 is commented.
My question is: how to make solid cubic with border and at the same time could be drag and drop?
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - draggable cubes</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #f0f0f0;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="js/three.js"></script>
<script src="js/TrackballControls.js"></script>
<script src="js/stats.min.js"></script>
<script>
var container, stats;
var camera, controls, scene, renderer;
var cubes = [];
var plane = new THREE.Plane();
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2(),
offset = new THREE.Vector3(),
intersection = new THREE.Vector3(),
INTERSECTED, SELECTED;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 10;
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
scene = new THREE.Scene();
scene.add( new THREE.AmbientLight( 0x505050 ) );
var geometry = new THREE.BoxGeometry( 2, 5, 7);
var hex = 0xff0000;
for ( var i = 0; i < geometry.faces.length; i++ ) {
geometry.faces[ i ].color.setHex( hex );
}
var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw: 0.5,wireframe:true } );
var cube = new THREE.Mesh( geometry, material );
cubes.push( cube );
var geometry2 = new THREE.BoxGeometry(2,4, 5);
var hex2 = 0x009fff;
for ( var i = 0; i < geometry2.faces.length; i++ ) {
geometry2.faces[ i ].color.setHex( hex2 );
}
var material2 = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw: 0.5,wireframe:true } );
var cube2 = new THREE.Mesh( geometry2, material2 );
cubes.push( cube2 );
var geometry3 = new THREE.BoxGeometry(1,3,4);
var hex3 = 0x0f0ff0;
for ( var i = 0; i < geometry3.faces.length; i++ ) {
geometry3.faces[ i ].color.setHex( hex3 );
}
/* var darkMaterial3= new THREE.MeshBasicMaterial( { color: 0xffffcc } );
var wireframeMaterial3= new THREE.MeshBasicMaterial( { color: 0x0f0000, wireframe: true, transparent: false } );
var multiMaterial3= [ darkMaterial3, wireframeMaterial3 ];
var cube3 = THREE.SceneUtils.createMultiMaterialObject(geometry3,multiMaterial3);*/
var material3 = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw: 0.5,wireframe:true } );
var cube3 = new THREE.Mesh( geometry3, material3 );
cubes.push( cube3 );
scene.add(cube);
scene.add(cube2);
scene.add(cube3);
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( 0xf0f0f0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.sortObjects = false;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
container.appendChild( renderer.domElement );
stats = new Stats();
container.appendChild( stats.dom );
renderer.domElement.addEventListener( 'mousemove', onDocumentMouseMove, false );
renderer.domElement.addEventListener( 'mousedown', onDocumentMouseDown, false );
renderer.domElement.addEventListener( 'mouseup', onDocumentMouseUp, false );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
if ( SELECTED ) {
if ( raycaster.ray.intersectPlane( plane, intersection ) ) {
SELECTED.position.copy( intersection.sub( offset ) );
}
return;
}
var intersects = raycaster.intersectObjects( cubes );
if ( intersects.length > 0 ) {
if ( INTERSECTED != intersects[ 0 ].object ) {
if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
INTERSECTED = intersects[ 0 ].object;
INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
plane.setFromNormalAndCoplanarPoint(
camera.getWorldDirection( plane.normal ),
INTERSECTED.position );
}
container.style.cursor = 'pointer';
} else {
if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
INTERSECTED = null;
container.style.cursor = 'auto';
}
}
function onDocumentMouseDown( event ) {
event.preventDefault();
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( cubes );
if ( intersects.length > 0 ) {
controls.enabled = false;
SELECTED = intersects[ 0 ].object;
if ( raycaster.ray.intersectPlane( plane, intersection ) ) {
offset.copy( intersection ).sub( SELECTED.position );
}
container.style.cursor = 'move';
}
}
function onDocumentMouseUp( event ) {
event.preventDefault();
controls.enabled = true;
if ( INTERSECTED ) {
SELECTED = null;
}
container.style.cursor = 'auto';
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
controls.update();
renderer.render( scene, camera );
}
</script>
</body>
</html>
Add a WireframeGeometry or EdgesGeometry as a child of each draggable object.
scene.add( object );
objects.push( object );
// wireframe
var geo = new THREE.EdgesGeometry( object.geometry );
var mat = new THREE.LineBasicMaterial( { color: 0x000000 } );
var wireframe = new THREE.LineSegments( geo, mat );
object.add( wireframe );
Also see this related answer.
three.js r.144
I suggest using EdgesHelper
this.scene.add(image3D);
edges = new THREE.EdgesHelper(image3D, 0x808080);
edges.material.linewidth = 3;
this.scene.add(edges);
Example:

three.js set background image

How to create a static background image?
For default background:
scene = new THREE.Scene();
// ...
renderer = new THREE.WebGLRenderer( { antialias: false } );
renderer.setClearColor( scene.fog.color, 1 );
How to set a image for scene.fog, or set opacity for clearcolor?
If you are trying to set a static background image (even if you rotate your main camera, the background doesn't change), you have to create 2 scenes and 2 cameras.
The first scene will be composed of a basic plane on which a texture is applied.
The second scene will have all your objects.
Here is a code that would do it :
<html>
<body>
<script src="Three.js"></script>
<script>
var color = 0x000000;
// Create your main scene
var scene = new THREE.Scene();
// Create your main camera
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// Create lights
var light = new THREE.PointLight(0xEEEEEE);
light.position.set(20, 0, 20);
scene.add(light);
var lightAmb = new THREE.AmbientLight(0x777777);
scene.add(lightAmb);
// Create your renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Create a cube
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshLambertMaterial({
color: 0xff00ff,
ambient: 0x121212,
emissive: 0x121212
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Set up the main camera
camera.position.z = 5;
// Load the background texture
var texture = THREE.ImageUtils.loadTexture( '1.jpg' );
var backgroundMesh = new THREE.Mesh(
new THREE.PlaneGeometry(2, 2, 0),
new THREE.MeshBasicMaterial({
map: texture
}));
backgroundMesh .material.depthTest = false;
backgroundMesh .material.depthWrite = false;
// Create your background scene
var backgroundScene = new THREE.Scene();
var backgroundCamera = new THREE.Camera();
backgroundScene .add(backgroundCamera );
backgroundScene .add(backgroundMesh );
// Rendering function
var render = function () {
requestAnimationFrame(render);
// Update the color to set
if (color < 0xdddddd) color += 0x0000ff;
// Update the cube color
cube.material.color.setHex(color);
// Update the cube rotations
cube.rotation.x += 0.05;
cube.rotation.y += 0.02;
renderer.autoClear = false;
renderer.clear();
renderer.render(backgroundScene , backgroundCamera );
renderer.render(scene, camera);
};
render();
</script>
</body>
</html>
**Demo right here **
Hope this helps.
NOTE (2014/06/28): This code works with the latest release of Three.js: R67
Use Texture loader to load a any image as texture and then apply that to scene like this:
//Load background texture
const loader = new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
{
scene.background = texture;
});
Result:
Demo:
See the Pen Flat Earth Three.JS by Hitesh Sahu (#hiteshsahu) on CodePen.
this run:
renderer = new THREE.WebGLRenderer({ antialias: false,alpha:true });
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0x000000, 0);
An background image can be set by setting the scene.background attribute of the THREE.Scene:
scene = new THREE.Scene();
bgTexture = loader.load("https://i.stack.imgur.com/vDUZz.jpg",
function ( texture ) {
var img = texture.image;
bgWidth= img.width;
bgHeight = img.height;
resize();
} );
scene.background = bgTexture;
bgTexture.wrapS = THREE.MirroredRepeatWrapping;
bgTexture.wrapT = THREE.MirroredRepeatWrapping;
The aspect ratio of the image can be adjusted to the aspect ratio of the canvas like this:
var aspect = window.innerWidth / window.innerHeight;
var texAspect = bgWidth / bgHeight;
var 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 );
See the code snippet:
(function onLoad() {
var container, loader, camera, scene, renderer, controls, bgTexture, bgWidth, bgHeight;
init();
animate();
function init() {
container = document.getElementById('container');
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
container.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 100);
camera.position.set(0, -4, -1.5);
loader = new THREE.TextureLoader();
loader.setCrossOrigin("");
scene = new THREE.Scene();
bgTexture = loader.load("https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/background.jpg",
function ( texture ) {
var img = texture.image;
bgWidth= img.width;
bgHeight = img.height;
resize();
}
);
scene.background = bgTexture;
bgTexture.wrapS = THREE.MirroredRepeatWrapping;
bgTexture.wrapT = THREE.MirroredRepeatWrapping;
scene.add(camera);
window.onresize = resize;
var ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
directionalLight.position.x = -0.75;
directionalLight.position.y = -0.5;
directionalLight.position.z = -1;
scene.add( directionalLight );
controls = new THREE.OrbitControls(camera, renderer.domElement);
createModel();
}
function createModel() {
var material = new THREE.MeshPhongMaterial({color:'#b090b0'});
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
}
function resize() {
var aspect = window.innerWidth / window.innerHeight;
var texAspect = bgWidth / bgHeight;
var 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();
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
})();
<script src="https://threejs.org/build/three.min.js"></script>
<!--script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.min.js"></script-->
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<div id="container"></div>
thank you ))
I found yet another solution:
<!DOCTYPE html>
<head>
<title>three.js webgl - orbit controls</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
color: #000;
font-family:Monospace;
font-size:13px;
text-align:center;
font-weight: bold;
background-image:url(./foto.jpg);
margin: 0px;
overflow: hidden;
}
#info {
color:#000;
position: absolute;
top: 0px; width: 100%;
padding: 5px;
}
a {
color: red;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">
three.js
</div>
<script src="./three.min.js"></script>
<script src="js/loaders/OBJLoader.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
<!--используем для вывода информации fps-->
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer;
var cross;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 2000 );
camera.position.z = 100;
controls = new THREE.OrbitControls( camera );
controls.addEventListener( 'change', render );
scene = new THREE.Scene();
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader( manager );
loader.load( './kos.jpg', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
// model
var loader = new THREE.OBJLoader( manager );
loader.load( './skull.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
}
} );
object.position.y = 10;
scene.add( object );
} );
// lights
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 );
scene.add( light );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( -1, -1, -1 );
scene.add( light );
light = new THREE.AmbientLight( 0xffffff );
scene.add( light );
renderer = new THREE.WebGLRenderer( { antialias: false } );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
container = document.getElementById( 'container' );
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
function animate() {
requestAnimationFrame( animate );
controls.update();
}
function render() {
renderer.render( scene, camera );
stats.update();
}
</script>
</body>
It seems rather late in the day to be adding any contribution to this thread but here is my 'hap'orth':
<head>
<meta charset=utf-8>
<title>Temple7</title>
<style>
body { margin: 0;
}
canvas { width: 100%; height: 100%;
background-image:url(Clouds.jpg);
}
</style>
</head>
This rather simplistic approach has its limitations. The .jpg image retains its pixel dimensions so that, for different sizes of the browser window one sees different amounts of the image. If the canvas size exceeds the size of the .jpg, then tiling occurs.

firstpersoncontrols delta is not defined

I test for use the firstpersoncontrols in three.js. but in copying examples to anderstand how it's work, i have always the same error in console : delta is not defined. if you are an explication :
<!-- upload librarie -->
<script src="../THREEJS03/build/three.min.js"></script>
<!-- upload les modes d'interactions -->
<script src="js/controls/FirstPersonControls.js"></script>
<script src="js/loaders/MTLLoader.js"></script>
<script src="js/loaders/OBJMTLLoader.js"></script>
<!-- upload la detection du webgl -->
<script src="js/Detector.js"></script>
<script>
//detection du webgl
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container;
var camera, cubeCamera, controls, scene, renderer;
var clock = new THREE.Clock();
init();
animate();
//////////////////////// SCENE /////////////////////////////////////
function init() {
// scene
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 3000 );
camera.position.x = 00;
camera.position.y = 80;
camera.position.z = 00;
controls = new THREE.FirstPersonControls( camera );
controls.movementSpeed = 1000;
controls.lookSpeed = 0.125;
controls.lookVertical = true;
controls.constrainVertical = false;
controls.verticalMin = 1.1;
controls.verticalMax = 2.2;
controls.noFly = true;
scene = new THREE.Scene();
scene.add( camera );
// light
// add ambient lighting
var ambientLight = new THREE.AmbientLight(0x020202);
scene.add(ambientLight);
var pointLight = new THREE.PointLight(0xffffff); //0xffaa00
pointLight.position.x = -300;
pointLight.position.y = 300;
pointLight.position.z = 500;
scene.add(pointLight);
//SKYBOX (only reflexive)
// Cubic Texture
var r = "models/world/";
var urls = [r + "posx.jpg", r + "negx.jpg",
r + "posy.jpg", r + "negy.jpg",
r + "posz.jpg", r + "negz.jpg"];
var textureCube = THREE.ImageUtils.loadTextureCube(urls);
////////////////////////// OBJET ////////////////////////////
var loader = new THREE.OBJMTLLoader();
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
object.position.y = 0;
scale = 1;
scene.add( object );
});
loader.load( 'models/macabann/obj/scene/scene01.obj', 'models/macabann/obj/scene/scene01.mtl' );
var material = new THREE.MeshPhongMaterial( {
//Environnement
envMap: textureCube,
combine: THREE.MixOperation,
//Color Application
side: THREE.DoubleSide,
shading: THREE.SmoothShading
});
///////////////////// FIN OBJET ///////////////////////
/////////////////// RENDERER //////////////////////
//type de rendu (antialias true or false)
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColorHex( 0xf3f3f3, 1 );
renderer.shadowMapEnabled = true;
//dimension du rendu
renderer.setSize( window.innerWidth, window.innerHeight );
// create wrapper object that contains three.js objects
container = document.createElement( 'div' );
document.body.appendChild( container );
container.appendChild( renderer.domElement );
///////////////////// FIN RENDERER ///////////////////////
//////////////////// WINDOWS ////////////////////////
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
controls.handleResize();
}
//////////////////////////FIN WINDOWS //////////////////////
function render() {
var delta = clock.getDelta();
time = clock.getElapsedTime() * 10;
}
function animate() {
requestAnimationFrame( animate );
controls.update(delta);
renderer.render( scene, camera );
}
</script>
thank to explications and answers
You have some problems in this part:
function render() {
var delta = clock.getDelta();
time = clock.getElapsedTime() * 10;
}
function animate() {
requestAnimationFrame( animate );
controls.update(delta);
renderer.render( scene, camera );
}
You define delta variable in render() function, which is outside of the skope of animate. Try moving those lines to the animate() function, like this:
function render() {
// is this function needed at all?
}
function animate() {
var delta = clock.getDelta();
time = clock.getElapsedTime() * 10;
requestAnimationFrame(animate);
controls.update(delta);
renderer.render( scene, camera );
}

Resources