three.js- Why it doesn't apply texture on object - javascript

I want to apply a texture on an object .
this is my code:
<html>
<head>
<title>My first Three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script src="three.min.js"></script>
<script src="OBJLoader.js"></script>
<script>
var container;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 100;
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 );
scene.add( directionalLight );
// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var texture = new THREE.Texture();
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 ) {
};
var loader = new THREE.ImageLoader( manager );
loader.load( 'bb.jpg', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
// model
var loader = new THREE.OBJLoader( manager );
loader.load( 'note4.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
}
} );
object.position.y = - 80;
scene.add( object );
}, onProgress, onError );
//
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX ) / 2;
mouseY = ( event.clientY - windowHalfY ) / 2;
}
//
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y += ( - mouseY - camera.position.y ) * .05;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
<div><canvas width="1360" height="150" style="width: 1360px; height: 150px;"></canvas></div>
</body>
</html>
All the js files ,texture and object file are in the same folder .
When I open the page, it gives me these errors . I tested it on firefox and chrome , firefox shows me these errors .
THREE.WebGLRenderer 69
THREE.WebGLRenderer: OES_texture_float extension not supported.
THREE.WebGLRenderer: OES_texture_float_linear extension not supported.
THREE.WebGLRenderer: OES_standard_derivatives extension not supported.
requestAnimationFrame is not defined
[Break On This Error] requestAnimationFrame( animate );
index.html (line 83)
bb.jpg 1 2
text is undefined
[Break On This Error] var lines = text.split( '\n' );
OBJLoader.js (line 195)
What am I doing wrong ?
Looking forward to hear from you

you're loading the textures with an image loader:
var loader = new THREE.ImageLoader( manager );
loader.load( 'bb.jpg', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
i've never worked with it because in most examples given textures are loaded in a different way:
var texture = THREE.ImageUtils.loadTexture('path/to/texture.png');

Related

Apply VideoTexture on a loaded .obj doesn't works three.js

I load an .obj exported from sketchup and representing a simple rectangle.
I want to apply a video texture on the front face of loaded .obj but it doesn't work and no error on the console. I'm quite stuck,the problem may come the UV, but I found nothing which can help me. I tried to use a VideoTexture but same problems.
here my code:
<div id="ThreeJS" style="position: absolute; left:0px; top:0px"></div>
<video id="video" autoplay muted loop crossOrigin="anonymous" webkit-playsinline style="display:none">
<source src="assets/output.mp4" type='video/mp4'>
</video>
<script>
var AMOUNT = 100;
var container;
var camera, scene, renderer;
var video, image, imageContext,
imageReflection, imageReflectionContext, imageReflectionGradient,
texture, textureReflection;
var mesh;
var mouseX = 0;
var mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xf0f0f0 );
video = document.createElement( 'video' );
// video.id = 'video';
// video.type = ' video/ogg; codecs="theora, vorbis" ';
video.src = "assets/output.mp4";
video.load(); // must call after setting/changing source
video.muted = true;
video.play();
//
image = document.createElement( 'canvas' );
image.width = 480;
image.height = 204;
imageContext = image.getContext( '2d' );
imageContext.fillStyle = '#000000';
imageContext.fillRect( 0, 0, 480, 204 );
texture = new THREE.Texture( image );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
imageReflection = document.createElement( 'canvas' );
imageReflection.width = 480;
imageReflection.height = 204;
imageReflectionContext = imageReflection.getContext( '2d' );
imageReflectionContext.fillStyle = '#000000';
imageReflectionContext.fillRect( 0, 0, 480, 204 );
imageReflectionGradient = imageReflectionContext.createLinearGradient( 0, 0, 0, 204 );
imageReflectionGradient.addColorStop( 0.2, 'rgba(240, 240, 240, 1)' );
imageReflectionGradient.addColorStop( 1, 'rgba(240, 240, 240, 0.8)' );
textureReflection = new THREE.Texture( imageReflection );
var materialReflection = new THREE.MeshBasicMaterial( { map: textureReflection, side: THREE.BackSide, overdraw: 0.5 } );
// var plane = new THREE.PlaneBufferGeometry( 480, 204, 4, 4 );
// mesh = new THREE.Mesh( plane, material );
// mesh.scale.x = mesh.scale.y = mesh.scale.z = 1;
// scene.add(mesh);
// mesh = new THREE.Mesh( plane, materialReflection );
// mesh.position.y = -306;
// mesh.rotation.x = - Math.PI;
// mesh.scale.x = mesh.scale.y = mesh.scale.z = 1.5;
// scene.add( mesh );
// this works
//model
var loader = new THREE.OBJLoader();
loader.load( 'assets/model3D.obj', function (object) {
var instance;
object.traverse( function (child) {
if ( child instanceof THREE.Mesh ) {
child.material = materialReflection;
child.material.needsUpdate = true;
// this doesn't works
}
});
object.position.y = - 80;
scene.add( object );
});
renderer = new THREE.CanvasRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
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 ) {
imageContext.drawImage( video, 0, 0 );
if ( texture ) texture.needsUpdate = true;
if ( textureReflection ) textureReflection.needsUpdate = true;
}
imageReflectionContext.drawImage( image, 0, 0 );
imageReflectionContext.fillStyle = imageReflectionGradient;
imageReflectionContext.fillRect( 0, 0, 480, 204 );
renderer.render( scene, camera );
}
</script>
here my .obj:
# Alias OBJ Model File
# Exported from SketchUp, (c) 2000-2012 Trimble Navigation Limited
# File units = meters
g Mesh1 Model
usemtl FrontColor
v 12.4942 0 7.12249
vt 491.898 280.413
vn 0 -1 0
v 1.26421 0 7.12249
vt 49.7719 280.413
v 1.26421 0 0.472495
vt 49.7719 18.6021
v 12.4942 0 0.472495
vt 491.898 18.6021
f 1/1/1 2/2/1 3/3/1 4/4/1
ps: I’m beginner in three.js

Three.js issue creating meshes outside of loader's load() function

I had difficulty exporting more than one texture using Blender's Three.js add-on, so had planned to work around it be separating the parts into separate meshes, but then came across the unexpected problem of the code not working when I created the meshes outside of the load() function. I've supplied an example below using a single model with a single mesh. The following works fine:
<!DOCTYPE html>
<html lang="en">
<head>
<title>working</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: #000000;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="js/build/three.min.js"></script>
<script src="js/loaders/ColladaLoader.js"></script>
<script src="js/Detector.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container;
var camera, scene, renderer, objects;
var scaleAdj = 100;
init();
animate();
function init()
{
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 20000 );
camera.position.set( 0, 500, 0 );
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xcce0ff, 10, 10000 );
var loader = new THREE.JSONLoader();
loader.load( 'cube.json', function ( geometry, materials )
{
var faceMaterial = new THREE.MultiMaterial( materials );
for ( var i = 0; i < 250; i ++ )
{
var x = ( ( i % 27 ) - 13.5 ) * (5 * scaleAdj) + THREE.Math.randFloatSpread( 300 * scaleAdj);
var z = ( Math.floor( i / 27 ) - 13.5 ) * (5 * scaleAdj) + THREE.Math.randFloatSpread( 300 * scaleAdj);
mesh = new THREE.Mesh( geometry, faceMaterial );
var s = THREE.Math.randFloat( 0.5, 2 ) * scaleAdj;
mesh.scale.set( s, s, s );
mesh.position.set( x, scaleAdj, z );
mesh.rotation.y = THREE.Math.randFloat( -0.25, 0.25 );
mesh.matrixAutoUpdate = false;
mesh.updateMatrix();
scene.add( mesh );
}
} );
scene.add( new THREE.AmbientLight( 0xffffff ) );
// ground
var textureLoader = new THREE.TextureLoader();
var groundTexture = textureLoader.load( "texture.jpg" );
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set( 40, 40 );
groundTexture.anisotropy = 16;
var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, map: groundTexture } );
var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000 ), groundMaterial );
mesh.position.y = 0;
mesh.rotation.x = - Math.PI / 2;
mesh.receiveShadow = true;
scene.add( mesh );
// Renderer
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( scene.fog.color );
container.appendChild( renderer.domElement );
// Events
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize( event ) {
renderer.setSize( window.innerWidth, window.innerHeight );
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
</html>
But this doesn't (I've annotated which sections contain the differences):
<!DOCTYPE html>
<html lang="en">
<head>
<title>not working</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: #000000;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="js/build/three.min.js"></script>
<script src="js/loaders/ColladaLoader.js"></script>
<script src="js/Detector.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
//--------------- difference number 1
var obj_geometry;
var obj_material;
//-----------------------------------
var container;
var camera, scene, renderer, objects;
var scaleAdj = 100;
init();
animate();
function init()
{
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 20000 );
camera.position.set( 0, 500, 0 );
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xcce0ff, 10, 10000 );
//-------------------difference number 2--------------------
var loader = new THREE.JSONLoader();
loader.load( 'cube.json', function ( geometry, material )
{
obj_geometry = geometry;
obj_material = material;
});
var faceMaterial = new THREE.MultiMaterial( obj_material);
for ( var i = 0; i < 250; i ++ )
{
var x = ( ( i % 27 ) - 13.5 ) * (5 * scaleAdj) + THREE.Math.randFloatSpread( 300 * scaleAdj);
var z = ( Math.floor( i / 27 ) - 13.5 ) * (5 * scaleAdj) + THREE.Math.randFloatSpread( 300 * scaleAdj);
mesh = new THREE.Mesh( obj_geometry, faceMaterial);
var s = THREE.Math.randFloat( 0.5, 2 ) * scaleAdj;
mesh.scale.set( s, s, s );
mesh.position.set( x, 0, z );
mesh.rotation.y = THREE.Math.randFloat( -0.25, 0.25 );
mesh.matrixAutoUpdate = false;
mesh.updateMatrix();
scene.add( mesh );
}
//--------------------------------------
scene.add( new THREE.AmbientLight( 0xffffff ) );
// ground
var textureLoader = new THREE.TextureLoader();
var groundTexture = textureLoader.load( "texture.jpg" );
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set( 40, 40 );
groundTexture.anisotropy = 16;
var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, map: groundTexture } );
var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000 ), groundMaterial );
mesh.position.y = 0;
mesh.rotation.x = - Math.PI / 2;
mesh.receiveShadow = true;
scene.add( mesh );
// Renderer
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( scene.fog.color );
container.appendChild( renderer.domElement );
// Events
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize( event ) {
renderer.setSize( window.innerWidth, window.innerHeight );
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
</html>
Here is a copy of the contents of the cube.json file:
{
"uvs":[[0,0,1,0,1,1,0,1]],
"faces":[43,0,1,2,3,0,0,1,2,3,0,1,2,3,43,4,7,6,5,0,0,1,2,3,4,5,6,7,43,0,4,5,1,0,0,1,2,3,0,4,7,1,43,1,5,6,2,0,0,1,2,3,1,7,6,2,43,2,6,7,3,0,0,1,2,3,2,6,5,3,43,4,0,3,7,0,0,1,2,3,4,0,3,5],
"normals":[0.577349,-0.577349,-0.577349,0.577349,-0.577349,0.577349,-0.577349,-0.577349,0.577349,-0.577349,-0.577349,-0.577349,0.577349,0.577349,-0.577349,-0.577349,0.577349,-0.577349,-0.577349,0.577349,0.577349,0.577349,0.577349,0.577349],
"metadata":{
"generator":"io_three",
"type":"Geometry",
"normals":8,
"vertices":8,
"uvs":1,
"version":3,
"materials":1,
"faces":6
},
"vertices":[1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1,0.999999,1,1,-1,1,1,-1,1,-1],
"materials":[{
"DbgName":"Material",
"colorSpecular":[0.5,0.5,0.5],
"DbgIndex":0,
"mapDiffuseWrap":["RepeatWrapping","RepeatWrapping"],
"mapDiffuse":"texture.jpg",
"shading":"phong",
"depthTest":true,
"opacity":1,
"transparent":false,
"colorDiffuse":[0.64,0.64,0.64],
"mapDiffuseAnisotropy":1,
"blending":"NormalBlending",
"depthWrite":true,
"visible":true,
"specularCoef":50,
"mapDiffuseRepeat":[1,1],
"colorEmissive":[0,0,0],
"wireframe":false,
"DbgColor":15658734
}],
"name":"CubeGeometry"
}
And here is an attached texture which could be used.
It might just be a trivial problem for some of the posters on here, and if so, thanks in advance for just letting me know what it is. If not, then the answer could be useful to a lot more people, and thanks for any help you can give on it.
You cant do this, asynchronously:
var obj_geometry; // === undefined
var myMesh = new THREE.Mesh( obj_geometry ); //because undefined, same as calling new THREE.Mesh();
obj_geometry = geometry;//does nothing, mesh has no idea about this happening
obj_material = material;
When you construct a mesh, you've given it undefined for geometry, so i think it just calls new Geometry() inside the constructor. This mesh has been created with a unique isntance of empty Geometry and has nothing to do with your obj_geometry.
The solution here is to do:
var obj_geometry = new THREE.Geometry();
var myMesh = new THREE.Mesh( obj_geometry ); //holds a reference to an empty "proxy"
then onLoad
loader.load( 'url' , function( geom ) {
obj_geometry.merge(geom); //"FILL PREVIOUSLY CREATED GEOMETRY WITH DATA"
obj_geometry.vertsNeedUpdate = true; // there's a few flags like this you need to turn on
}
OR
var myMesh = new THREE.Mesh();
loader.load( 'url', function( geom ) {
myMesh.geometry = geom; //"PUT THE JUST CREATED GEOMETRY IN THE RIGHT PLACE"
//myOtherMesh.geometry = geom; //if you have more places where this needs to end up
//myThirdMesh.geometry = geom; //gets very cumbersome
}
Both are pretty cumbersome and not very intuitive :( i really dislike this part of three.js.
Thanks to help from pailhead, pointing out the asynchronous issue I made the following modification to the code and found that it worked. Surprisingly the count that I added doesn't seem to raise above 0, but I am assuming that it was because it was quite a close run thing.
<!DOCTYPE html>
<html lang="en">
<head>
<title>asynchronous working</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: #000000;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="build/three.min.js"></script>
<script>
//--------------- difference number 1
var obj_geometry;
var obj_material;
var loaded = false;
//-----------------------------------
var container;
var camera, scene, renderer, objects;
var scaleAdj = 100;
init();
animate();
function init()
{
container = document.createElement( 'div' );
document.body.appendChild( container );
//-----an info display
info = document.createElement( 'div' );
info.id = "info";
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
container.appendChild(info);
//-----------------
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 20000 );
camera.position.set( 0, 500, 0 );
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xcce0ff, 10, 10000 );
//-------------------difference number 2--------------------
var loader = new THREE.JSONLoader();
loader.load( 'cube.json', function ( geometry, material )
{
obj_geometry = geometry;
obj_material = material;
loaded = true;
});
var notLoadedCount = 0;
var processor = setInterval(function()
{
if(!loaded)
{
notLoadedCount++;
}
else
{
var faceMaterial = new THREE.MultiMaterial( obj_material);
for ( var i = 0; i < 250; i ++ )
{
var x = ( ( i % 27 ) - 13.5 ) * (5 * scaleAdj) + THREE.Math.randFloatSpread( 300 * scaleAdj);
var z = ( Math.floor( i / 27 ) - 13.5 ) * (5 * scaleAdj) + THREE.Math.randFloatSpread( 300 * scaleAdj);
mesh = new THREE.Mesh( obj_geometry, faceMaterial);
var s = THREE.Math.randFloat( 0.5, 2 ) * scaleAdj;
mesh.scale.set( s, s, s );
mesh.position.set( x, 0, z );
mesh.rotation.y = THREE.Math.randFloat( -0.25, 0.25 );
mesh.matrixAutoUpdate = false;
mesh.updateMatrix();
scene.add( mesh );
info.innerHTML= '*not loaded count = ' + notLoadedCount;
}
clearInterval(processor);
}
}, 100);
//--------------------------------------
scene.add( new THREE.AmbientLight( 0xffffff ) );
// ground
var textureLoader = new THREE.TextureLoader();
var groundTexture = textureLoader.load( "texture.jpg" );
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set( 40, 40 );
groundTexture.anisotropy = 16;
var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, map: groundTexture } );
var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000 ), groundMaterial );
mesh.position.y = 0;
mesh.rotation.x = - Math.PI / 2;
mesh.receiveShadow = true;
scene.add( mesh );
// Renderer
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( scene.fog.color );
container.appendChild( renderer.domElement );
// Events
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize( event ) {
renderer.setSize( window.innerWidth, window.innerHeight );
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
</html>
Thanks for the help with this, hopefully it helps others too. If there are any problems with this resolution that anybody notices, please let me know. Thanks.

Three.js OBJ loader not working on codepen?

I'm a trying to load an OBJ file on Three.js, its working on my local, and when I deploy the files on my server it's working fine :
http://hafsadanguir.com/THREEJS/
but it's not working on codepen : http://codepen.io/hafsadanguir/pen/RaJaPZ
var container;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth/ 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 20, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 900;
camera.position.x = -1000;
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x404040 ); //This creates an Ambientlight with a color.
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
directionalLight.position.set( 0, 0, 1 );
scene.add( directionalLight );
// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var texture = new THREE.Texture();
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 ) {
};
var loader = new THREE.ImageLoader( manager );
loader.load('http://hafsadanguir.com/THREEJS/textures/red.jpg', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
// model
var loader = new THREE.OBJLoader( manager );
loader.load('http://hafsadanguir.com/THREEJS/obj/Heart.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
}
} );
object.position.y = -150;
scene.add( object );
}, onProgress, onError );
//
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX ) / 2;
mouseY = ( event.clientY - windowHalfY ) / 2;
}
//
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
//camera.position.x += ( mouseX - camera.position.x ) * .005;
//camera.position.y += ( - mouseY - camera.position.y ) * .005;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
Someone can help please, it's my first time using three.js :)
I have the loader working using the latest version of ThreeJS. You are using version 73, you should be using v75:
http://codepen.io/aaronfranco/pen/LNrZQg
https://cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.min.js
Your server does not allow you to access those object files. I'm getting CORS error from your server. If load them from the same domain, then it should work.
But without proper CORS, allow origin headers, you won't be able to use them in CodePen.
> XMLHttpRequest cannot load
> http://hafsadanguir.com/THREEJS/obj/Heart.obj. No
> 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'http://s.codepen.io' is therefore not allowed
> access.

Adding clickable image to a mesh

This may be a really stupid question, but I am new to three.js and while I've gotten the obj file to load on the web and be controllable via mouse, I'm not quite sure how to handle the next step.
What I'd really like to do is overlay a clickable .jpg or .png file over a section of the existing mesh linking out to some web pages I already have completed. How would I go about doing this? I'd appreciate it if someone could point me to an example or let me know if it's not doable so I can look for possible alternatives.
The code I currently have is below -- it's mostly cobbled together from online example so forgive me if it seems redundant or inelegant.
var container, stats;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
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;
controls.keys = [ 65, 83, 68 ];
controls.addEventListener( render );
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0xFFFFFF );
scene.add( ambient );
/*var directionalLight = new THREE.DirectionalLight( 0xffffff );
directionalLight.position.set( 1, 1, 0 ).normalize();
scene.add( directionalLight );*/
var hemisphereLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, .70);
scene.add( hemisphereLight );
// model
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() );
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var loader = new THREE.OBJMTLLoader();
loader.load( 'obj/test/test_model.obj', 'obj/test/test_model.mtl', function ( object ) {
object.scale = new THREE.Vector3( 25, 25, 25 );
//object.position.y = - 80;
scene.add( object );
}, onProgress, onError );
//
renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
controls.handleResize();
}
function onDocumentMouseMove( event ) {
// mouseX = ( event.clientX - windowHalfX ) / 2;
// mouseY = ( event.clientY - windowHalfY ) / 2;
}
//
function animate() {
requestAnimationFrame( animate );
controls.update();
render();
}
function render() {
//camera.position.x += ( mouseX - camera.position.x ) * .05;
//camera.position.y += ( - mouseY - camera.position.y ) * .05;
//camera.lookAt( scene.position );
renderer.render( scene, camera );
}
In your onDocumentMouseMove - or in a click event - you must compute a ray-picking intersection with http://threejs.org/docs/#Reference/Core/Raycaster and handle the reaction from there.
There are multiples examples of this, in the Three.js examples (like http://threejs.org/examples/#webgl_geometry_terrain_raycast) and on StackOverflow.
A very naive solution could be:
// note that you may have to use other properties if the renderer is not fullscreen"
// like here http://stackoverflow.com/questions/13542175/three-js-ray-intersect-fails-by-adding-div
var mouseX = ( event.clientX / window.innerWidth ) * 2 - 1;
var mouseY = -( event.clientY / window.innerHeight ) * 2 + 1;
var vector = new THREE.Vector3( mouseX, mouseY, camera.near );
// Convert the [-1, 1] screen coordinate into a world coordinate on the near plane
vector.unproject( camera );
var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
// See if the ray from the camera into the world hits one of our meshes
var intersects = raycaster.intersectObjects( scene, true ); // true for recursive
// Toggle rotation bool for meshes that we clicked
if ( intersects.length > 0 ) {
var clickedObject = intersects[ 0 ].object;
// here, handle the clickedObject properties to react accordingly
// show an overlay, jump to a page, etc..
}

Animating obj files with OBJLoader in Three.js

I currently have to do an animation with obj files. I want to rotate horizontally the loaded ribs. Is it just POSSIBLE to animate obj files ? If so, how do you do that ? I search all over the web, the only animation examples I found were made using JSONLoader, wich I don't use. Here is my code :
window.onload = function() {
var container, stats;
var camera, scene, renderer, object;
var windowHalfX;
var windowHalfY;
init();
animate();
function init() {
width = 500;
height = 500;
windowHalfX=width/2;
windowHalfY=height/2;
camera = new THREE.PerspectiveCamera( 45, width / height, 1, 2000 );
camera.position.z = 300;
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 1, 1 );
scene.add( directionalLight );
var loader = new THREE.OBJMTLLoader();
for ( var i = 1; i < 13; i ++ ) {
var chem = './three/obj/Cotes/left/CG';
if (i<10) {
var nomcote = chem+'0'+i+'.obj';
var matcote = chem+'0'+i+'.mtl';
}
else{
var nomcote = chem+i+'.obj';
var matcote = chem+i+'.mtl';
}
loader.load( nomcote, matcote, function ( object ) {
object.position.y = - 70;
object.name = "cotesG"+i;
scene.add( object );
} );
}
for ( var i = 1; i < 13; i ++ ) {
var chem = './three/obj/Cotes/right/CD';
if (i<10) {
var nomcote = chem+'0'+i+'.obj';
var matcote = chem+'0'+i+'.mtl';
}
else{
var nomcote = chem+i+'.obj';
var matcote = chem+i+'.mtl';
}
loader.load( nomcote, matcote, function ( object ) {
object.position.y = - 70;
object.name = "cotesD"+i;
scene.add( object );
} );
}
renderer = new THREE.WebGLRenderer();
renderer.setSize( width, height );
controls = new THREE.OrbitControls(camera,renderer.domElement);
controls.addEventListener( 'change', render );
document.body.appendChild( renderer.domElement );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = width / 2;
windowHalfY = height / 2;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize( width, height );
render();
}
function animate() {
requestAnimationFrame( animate );
controls.update();
}
function render() {
// camera.lookAt( scene.position );
renderer.render( scene, camera );
}
}

Categories

Resources