firstpersoncontrols delta is not defined - controls

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 );
}

Related

Adding DeviceOrientationControls to a GLTF GLB object

I am using Three.JS and have gotten a .glb file to display beautifully with some mouse movement.
I'm now trying to add DeviceOrientationControls to my GLtf/GLB scene, so I can move around the scene when moving the mobile phone around, however I can't quite work it out.
No matter what I try I always get one error or another.
I have tried adapting the code from this example: https://threejs.org/examples/misc_controls_deviceorientation.html
This is my current code without any DeviceOrientationControls code added:
HTML
<!-- three.min.js r87 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<!-- GLTFLoader.js -->
<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js#r92/examples/js/loaders/GLTFLoader.js"></script>
<!-- Orientation Controls -->
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/DeviceOrientationControls.js"></script>
<div id="overlay">
<div>
<button id="startButton">Start Demo</button>
<p>Using device orientation might require a user interaction.</p>
</div>
</div>
<div class="single-object">
<div id="container"></div>
JS
window.addEventListener("load", loadGltf, false);
window.addEventListener("resize", onWindowResize, false);
const progressBar = document.querySelector("progress");
const gltfStore = {};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x111111);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// Attach to container
container = document.getElementById( 'container' );
//Setup camera
const camera = new THREE.PerspectiveCamera(
75, window.innerWidth / window.innerHeight,0.1, 1000 );
camera.position.set(0, 0, 0);
camera.lookAt(0, 0, 5);
windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
mouseX = 0,
mouseY = 0;
//Re-establish camera view on window resize
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
//Lighting
const lightFill = new THREE.PointLight(0xffffff, 1, 500);
lightFill.position.set(0, 0, 5);
scene.add(lightFill);
const lightKey = new THREE.PointLight(0xffffff, 1, 500);
lightKey.position.set(20, 0, 20);
scene.add(lightKey);
const loader = new THREE.GLTFLoader();
// Device Orientation
// Load the GLB file
function loadGltf() {
loader.load(
"<?php echo get_template_directory_uri();?>/objects/SM_LookDev_TextureTest_FromFBX.glb",
function(gltf) {
scene.add(gltf.scene);
mesh = gltf.scene;
gltf.scene.children[0];
gltfStore.scene = gltf.scene;
// Set listener
document.addEventListener("mousemove", onMouseMove);
}
);
container.appendChild(renderer.domElement);
// Mouse movement
function onMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 10;
mouseY = (event.clientY - windowHalfY) / 30;
}
function animate() {
requestAnimationFrame(animate);
// Adjust mouse and scene position
camera.position.x += (mouseX - camera.position.x) * .0005;
camera.position.y += (-mouseY - camera.position.y) * .0003;
camera.lookAt(0,0,10);
renderer.render(scene, camera);
}
animate();
}
I have gathered from the examples that I need to add these lines (I think):
controls = new DeviceOrientationControls( camera );
controls.update();
and the below for the start button...
var startButton = document.getElementById( 'startButton' );
startButton.addEventListener( 'click', function () {
init();
animate();
}, false );
EDIT
Below is an example of where I have tried to add the lines, but have not worked successfully.
window.addEventListener("load", loadGltf, false);
window.addEventListener("resize", onWindowResize, false);
const progressBar = document.querySelector("progress");
// Add Start Button
var startButton = document.getElementById( 'startButton' );
startButton.addEventListener( 'click', function () {
init();
animate();
}, false );
const gltfStore = {};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x111111);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// Attach to container
container = document.getElementById( 'container' );
//Setup camera
const camera = new THREE.PerspectiveCamera(
75, window.innerWidth / window.innerHeight,0.1, 1000 );
camera.position.set(0, 0, 0);
camera.lookAt(0, 0, 5);
windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
mouseX = 0,
mouseY = 0;
//Re-establish camera view on window resize
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
//Lighting
const lightFill = new THREE.PointLight(0xffffff, 1, 500);
lightFill.position.set(0, 0, 5);
scene.add(lightFill);
const lightKey = new THREE.PointLight(0xffffff, 1, 500);
lightKey.position.set(20, 0, 20);
scene.add(lightKey);
const loader = new THREE.GLTFLoader();
// Added Device Orientation Controls
controls = new DeviceOrientationControls( camera );
// Load the GLB file
function loadGltf() {
loader.load(
"<?php echo get_template_directory_uri();?>/objects/SM_LookDev_TextureTest_FromFBX.glb",
function(gltf) {
scene.add(gltf.scene);
mesh = gltf.scene;
gltf.scene.children[0];
gltfStore.scene = gltf.scene;
// Set listener
document.addEventListener("mousemove", onMouseMove);
}
);
container.appendChild(renderer.domElement);
// Mouse movement
function onMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 10;
mouseY = (event.clientY - windowHalfY) / 30;
}
function animate() {
requestAnimationFrame(animate);
// Adjust mouse and scene position
camera.position.x += (mouseX - camera.position.x) * .0005;
camera.position.y += (-mouseY - camera.position.y) * .0003;
camera.lookAt(0,0,10);
// Add Controls Update
controls.update();
renderer.render(scene, camera);
}
animate();
}
When adding the lines like this, I get these 2 error messages:
Uncaught TypeError: Cannot read property 'addEventListener' of null
and
Uncaught ReferenceError: Cannot access 'loader' before initialization at loadGltf
So, I am unsure how to actually add these lines into my specific code to get it to work?
Any assistance would be appreciated
It's hard to tell exactly the reason why it's not working, especially since your question includes so much extraneous code. You should try to ask your questions with a minimal reproducible example.
First, you're importing your <scripts> from varying sources, and varying versions. The Three.js and GLTFLoader you're loading is r92, but the DeviceOrientationControls script doesn't specify a version, so it's loading the latest at r112, which might no longer be compatible with ThreeJS r92.
Secondly, you're using:
controls = new DeviceOrientationControls( camera );, when it should be:
controls = new THREE.DeviceOrientationControls( camera );
Finally, make sure you organize your code, and call your functions in a sequential manner. Is loadGltf() being called before you initiate const loader = new THREE.GLTFLoader()? Does startButton exist, and is it defined before you call startButton.addEventListener();?
Here is a minimal example implementing the orientation controls: Notice that both scripts are being imported from the same source with r92 to ensure compatibility.
window.addEventListener("resize", resize);
const renderer = new THREE.WebGLRenderer({canvas: document.querySelector("canvas")});
const camera = new THREE.PerspectiveCamera(60, 1, 1, 1000);
const controls = new THREE.DeviceOrientationControls( camera );
// Make a scene with geometry
const scene = new THREE.Scene();
const geometry = new THREE.DodecahedronBufferGeometry(100,1);
const material = new THREE.MeshBasicMaterial({
color: 0xff9900,
wireframe: true,
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
function resize() {
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
function animate(time) {
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
resize();
animate(0);
body { margin: 0; }
<canvas></canvas>
<!-- three.min.js r92 -->
<script src="https://cdn.jsdelivr.net/npm/three#0.92/build/three.min.js"></script>
<!-- Orientation Controls r92 -->
<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js#r92/examples/js/controls/DeviceOrientationControls.js"></script>
Note:
Apple disabled gyroscope access by default since iOS 12.2, so you'll have to enable it in settings when testing. See here for a discussion on the matter.

Video transition in Three.js

I want to play multiple videos in Three.js environment. I have finished loading video as texture and play it below and stuck at how to implement to load multiple video textures and play. Also adding some transition into it :(. Hope anyone can help me , give me some suggestions or right direction to do it. I'm fresh to webGL and Three.js.
// MAIN
// standard global variables
var container, scene, camera, renderer, controls, stats;
// custom global variables
var video, videoImage, videoImageContext, videoTexture;
var mouseX = 0;
var mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight;
init();
animate();
// FUNCTIONS
function init() {
// SCENE
scene = new THREE.Scene();
// CAMERA
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0,200,500);
camera.lookAt(scene.position);
// RENDERER
if ( Detector.webgl )
renderer = new THREE.WebGLRenderer( {antialias:true} );
else
renderer = new THREE.CanvasRenderer();
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
renderer.setClearColor (0xFFFFFF, 1);
container = document.getElementById( 'ThreeJS' );
container.appendChild( renderer.domElement );
// CONTROLS
// controls = new THREE.OrbitControls( camera, renderer.domElement );
// EVENTS
THREEx.WindowResize(renderer, camera);
// LIGHT
// var light = new THREE.PointLight(0xffffff);
// light.position.set(0,250,0);
// scene.add(light);
// FLOOR
var floorTexture = new THREE.ImageUtils.loadTexture( 'logo.jpg' );
var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var floorGeometry = new THREE.PlaneGeometry(500, 500, 0, 0);
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
// floor.wrapS = THREE.RepeatWrapping;
// floor.position.y = -0.5;
// floor.rotation.x = - (Math.PI / 2);
floor.position.y = -100;
floor.rotation.x = - (Math.PI / 2);
scene.add(floor);
///////////
// VIDEO //
///////////
// create the video element
video = document.createElement( 'video' );
// video.id = 'video';
// video.type = ' video/ogg; codecs="theora, vorbis" ';
video.src = "video3.mp4";
video.load(); // must call after setting/changing source
video.play();
// alternative method --
// create DIV in HTML:
// <video id="myVideo" autoplay style="display:none">
// <source src="videos/sintel.ogv" type='video/ogg; codecs="theora, vorbis"'>
// </video>
// and set JS variable:
// video = document.getElementById( 'myVideo' );
videoImage = document.createElement( 'canvas' );
videoImage.width = 1280;
videoImage.height = 546;
videoImageContext = videoImage.getContext( '2d' );
// background color if no video present
videoImageContext.fillStyle = '#000000';
videoImageContext.fillRect( 0, 0, videoImage.width, videoImage.height );
videoTexture = new THREE.Texture( videoImage );
videoTexture.minFilter = THREE.LinearFilter;
videoTexture.magFilter = THREE.LinearFilter;
var movieMaterial = new THREE.MeshBasicMaterial( { map: videoTexture, overdraw: true, side:THREE.DoubleSide } );
// the geometry on which the movie will be displayed;
// movie image will be scaled to fit these dimensions.
var movieGeometry = new THREE.PlaneGeometry( 600, 300, 4, 4 );
var movieScreen = new THREE.Mesh( movieGeometry, movieMaterial );
movieScreen.position.set(0,50,-200);
scene.add(movieScreen);
camera.position.set(0,200,450);
var vector = new THREE.Vector3(0,200,450);
camera.lookAt(movieScreen.position);
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
}
function onDocumentMouseMove(event) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY ) * 0.2;
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * 0.05;
camera.position.y += ( - mouseY - camera.position.y ) * 0.05;
camera.lookAt(scene.position);
if ( video.readyState === video.HAVE_ENOUGH_DATA )
{
videoImageContext.drawImage( video, 0, 0 );
if ( videoTexture )
videoTexture.needsUpdate = true;
}
renderer.render( scene, camera );
}

THREE.OBJLoader can not display obj file?

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));

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.

Cannot load textures

I'm struggleing with texture load issues.
All I see is a black sphere. :(
Any help would be awesome! Do i make something wrong?
Browser downloads the image, no issues on the console.
Checked in every browser with the same result.
OS: Mac 10.8.2
Here is my code:
<html>
<head>
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/three.min.js"></script>
</head>
<body>
<div id="container">
</div>
<script>
function addSpaceSphere( ){
// set up the sphere vars
var radius = 125,
segments = 16,
rings = 16;
var material = new THREE.MeshPhongMaterial({
color:0xFFFFFF,
map: THREE.ImageUtils.loadTexture( 'textures/SPACE014S.png' ) ,
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings
),
material
);
// add the sphere to the scene
scene.add(sphere);
}
function addLights(){
// create a point light
var ambient = new THREE.AmbientLight( 0xFFFFFF );
scene.add( ambient );
// create a point light
var pointLight = new THREE.PointLight(0xFFFFFF);
// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
// add to the scene
scene.add(pointLight);
}
function createScene(){
// add the camera to the scene
scene.add(camera);
// the camera starts at 0,0,0
// so pull it back
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 300;
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
addSpaceSphere( );
addLights();
renderer.render(scene, camera);
}
function onWindowResize( event ) {
var newEarthContainerWidth = earthContainer.offsetWidth;
var newWindowHeight = window.innerHeight;
var newScale = newEarthContainerWidth / earthContainerWidth;
sphere.geometry.__dirtyVertices = true;
sphere.scale.x = sphere.scale.y = sphere.scale.z = newScale;
renderer.setSize( newEarthContainerWidth, newWindowHeight );
camera.aspect = newEarthContainerWidth / newWindowHeight;
camera.updateProjectionMatrix();
camera.radius = ( newEarthContainerWidth + newWindowHeight ) / 4;
}
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var $container = $('#container');
// create a WebGL renderer, camera
// and a scene
//var renderer = new THREE.CanvasRenderer();
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera(
VIEW_ANGLE, ASPECT, NEAR, FAR
);
var scene = new THREE.Scene();
createScene();
window.addEventListener( 'resize', onWindowResize, false );
</script>
</body>
You are calling
renderer.render( scene, camera );
only once, and probably before the texture completes loading.
Add an animation loop.
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();

Resources