Animating obj files with OBJLoader in Three.js - javascript

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

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

Make css3d rendering plane to be act as a floor in 3JS?

My requirement is to make a css3d rendering plane to be act as a floor. And a 3d cube should be on top of the plane. Following I have attached the code which I tried.Both plane and the cube shares the same scene and camera.But renders are different. But I couldn't place the 3d cube on top of the plane and rotation of the plane and cube are different.
<!DOCTYPE html>
<html lang="en">
<head>
<title>3JS CODE</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/controls/TrackballControls.js"></script>
<script src="js/renderers/CSS3DRenderer.js"></script>
<script src="js/libs/stats.min.js"></script>
<script>
var HtmlElement = function ( id, x, y, z, rx ) {
var div = document.createElement( 'div' );
div.innerHTML = "Hello";
div.id = id; //'googleMap';
div.style.width = '1200px';
div.style.height = '950px';
div.style.backgroundColor = 'blue';
var object = new THREE.CSS3DObject( div );
object.position.set( x, y, z );
object.rotation.x = rx;
return object;
};
</script>
<script>
var container, stats;
var camera, controls, mapScene, group, renderer1,renderer2;
var objects = [];
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 5000 );
camera.position.z = 1000;
camera.position.set(0.18348775328760136, -334.5971567493426, 800.8398185862801);
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 3.0;
controls.zoomSpeed = 2.2;
controls.panSpeed = 2.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 1.3;
mapScene = new THREE.Scene();
// scene.background = new THREE.Color( 0xf0f0f0 );
group = new THREE.Group();
var mapObject = new HtmlElement( 'googleMap', 0, 0, 240, 270 );
group.add( mapObject );
///////////////
var geometry = new THREE.BoxGeometry( 200, 200, 200 );
for ( var i = 0; i < geometry.faces.length; i += 2 ) {
var hex = Math.random() * 0xffffff;
geometry.faces[ i ].color.setHex( hex );
geometry.faces[ i + 1 ].color.setHex( hex );
}
var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw: 0.5 } );
cube = new THREE.Mesh( geometry, material );
cube.position.x = 0;
cube.position.y = -300;
cube.position.z = 500;
group.add( cube );
mapScene.add( group );
// renderer
renderer1 = new THREE.CSS3DRenderer();
renderer1.setSize( window.innerWidth, window.innerHeight );
renderer1.domElement.style.position = 'absolute';
renderer1.domElement.style.top = 0;
container.appendChild( renderer1.domElement );
renderer2 = new THREE.WebGLRenderer( { antialias: true } );
renderer2.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer2.domElement );
stats = new Stats();
container.appendChild( stats.dom );
window.addEventListener( 'resize', onWindowResize, false );
render();
// initMap();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer1.setSize( window.innerWidth, window.innerHeight );
renderer2.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
controls.update();
renderer1.render( mapScene, camera );
renderer2.render( mapScene, camera );
}
</script>
</body>
</html>
here's the output
THREE.CSS3DObject does not care about the depth buffer of the WebGLRenderingContext. It has no clue about the depth buffer or even depth test. The order of CSS objects can be defined by the z-index.
You try to mix two completely different technologies, which won't interact together in that way.
But you can still make it work.
For this you have to define the z-index of the CSS3DRenderer element lower then the z-index of the WebGLRenderer element so that the WebGLRenderer draws "in front of" the CSS3DRenderer. Further transparency has to be enabled for the WebGLRenderer:
renderer1 = new THREE.CSS3DRenderer();
renderer1.setSize( window.innerWidth, window.innerHeight );
renderer1.domElement.style.position = 'absolute';
renderer1.domElement.style.zIndex = 0;
renderer1.domElement.style.top = 0;
container.appendChild( renderer1.domElement );
renderer2 = new THREE.WebGLRenderer( { antialias: true, alpha:true } );
renderer2.setSize( window.innerWidth, window.innerHeight );
renderer2.domElement.style.position = 'absolute';
renderer2.domElement.style.zIndex = 1;
renderer2.domElement.style.top = 0;
container.appendChild( renderer2.domElement );
Then you have to ensure that the WebGLRenderer takes care of the CSS3DObject. Technically this can't be done. But you can trick the system.
You can render a completely transparent plane, with equal size an at equal position, as the CSS3DObject in the WebGLRenderer:
var HtmlElement = function ( id, x, y, z, w, h ) {
var div = document.createElement( 'div' );
div.innerHTML = "Hello";
div.id = id; //'googleMap';
div.style.width = w + 'px';
div.style.height = h + 'px';
div.style.backgroundColor = 'blue';
var object = new THREE.CSS3DObject( div );
object.position.set( x, y, z );
return object;
};
var WebGlObject = function ( x, y, z, w, h ) {
var material = new THREE.MeshBasicMaterial({
color: 0x0000000,
opacity: 0.0,
side: THREE.DoubleSide
});
var geometry = new THREE.PlaneGeometry(w, h);
var mesh = new THREE.Mesh(geometry, material);
mesh.position.x = x;
mesh.position.y = y;
mesh.position.z = z;
return mesh;
};
var mapObject = HtmlElement('googleMap', 0, 0, 0, 800, 800);
var planeMesh = WebGlObject( 0, 0, 0, 800, 800);
See the example, which is based on the code of your question:
var HtmlElement = function ( id, x, y, z, w, h ) {
var div = document.createElement( 'div' );
//div.innerHTML = "Hello";
div.id = id; //'googleMap';
div.style.width = w + 'px';
div.style.height = h + 'px';
div.style.backgroundColor = 'lightblue';
div.style.color = "red";
div.style.fontSize="200px";
div.style.textAlign="center";
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.google.com/maps/embed");
iframe.style.width = w + "px";
iframe.style.height = h + "px";
div.appendChild(iframe);
var object = new THREE.CSS3DObject( div );
object.position.set( x, y, z );
return object;
};
var WebGlObject = function ( x, y, z, w, h ) {
var material = new THREE.MeshBasicMaterial({
color: 0x0000000,
opacity: 0.0,
side: THREE.DoubleSide
});
var geometry = new THREE.PlaneGeometry(w, h);
var mesh = new THREE.Mesh(geometry, material);
mesh.position.x = x;
mesh.position.y = y;
mesh.position.z = z;
return mesh;
};
var container, stats;
var camera, controls, mapScene, group, renderer1,renderer2;
var objects = [];
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 5000 );
camera.position.set(-600, 300, 700);
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 3.0;
controls.zoomSpeed = 2.2;
controls.panSpeed = 2.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 1.3;
mapScene = new THREE.Scene();
// scene.background = new THREE.Color( 0xf0f0f0 );
group = new THREE.Group();
group.renderOrder=1;
var mapObject = HtmlElement( 'googleMap', 0, 0, 0, 800, 800 );
var planeMesh = WebGlObject(0, 0, 0, 800, 800);
group.add( mapObject );
var geometry = new THREE.BoxGeometry( 200, 200, 200 );
for ( var i = 0; i < geometry.faces.length; i += 2 ) {
var hex = Math.random() * 0xffffff;
geometry.faces[ i ].color.setHex( hex );
geometry.faces[ i + 1 ].color.setHex( hex );
}
var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw: 0.5 } );
cube = new THREE.Mesh( geometry, material );
cube.position.x = 0;
cube.position.y = 0;
cube.position.z = 102;
group.add( cube );
group.add( planeMesh );
mapScene.add( group );
// renderer
renderer1 = new THREE.CSS3DRenderer();
renderer1.setSize( window.innerWidth, window.innerHeight );
renderer1.domElement.style.position = 'absolute';
renderer1.domElement.style.zIndex = 0;
renderer1.domElement.style.top = 0;
container.appendChild( renderer1.domElement );
renderer2 = new THREE.WebGLRenderer( { antialias: true, alpha:true } );
renderer2.setSize( window.innerWidth, window.innerHeight );
renderer2.domElement.style.position = 'absolute';
renderer2.domElement.style.zIndex = 1;
renderer2.domElement.style.top = 0;
container.appendChild( renderer2.domElement );
window.addEventListener( 'resize', onWindowResize, false );
render();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer1.setSize( window.innerWidth, window.innerHeight );
renderer2.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
controls.update();
renderer2.render( mapScene, camera );
renderer1.render( mapScene, 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/TrackballControls.js"></script>
<script src="https://threejs.org/examples/js/renderers/CSS3DRenderer.js"></script>

Three JS Cannot read property 'add' of undefined

Working on a project where on a button click script fetches a .svg and a .obj. Currently the button finds the .svg and the .obj but then spits out this error.
Uncaught TypeError: Cannot read property 'add' of undefined
Here is the code for the button, all other ThreeJS variables and calls are in the HTML and finish loading before the button is clicked.
function item(section, callback){
var tmp = itemName.split('-');
var cut = tmp[tmp.length-2];
var styleNo = tmp[tmp.length-1];
var path;
var model;
var loader = new THREE.OBJLoader( manager );
if (_product.svgPathAbsolute) {
path = itemName + '.svg';
model = styleCode + '.obj';
} else {
path = _product[section].svgPath + _product.name.toLowerCase() + '/' + cut.toLowerCase() + '/' + itemName + '.svg';
model = _product[section].svgPath + _product.name.toLowerCase() + '/' + cut.toLowerCase() + '/' + styleCode + '.obj';
}
loader.load( model, function ( object ) {
object.traverse(function(node){
if(node.material){
node.material.side = THREE.DoubleSide;
node.material = material;
}
});
object.position.y = -100;
geometry = object;
scene.add(geometry);
});
$.get(path, function (svg) {
_html[section] = svgToString(svg);
callback(section);
});
}
Included in HTML
<script>
var camera, scene, renderer, controls;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var geometry;
var material;
var svg = document.getElementById("svg-holder").querySelector("svg");
var img = document.createElement("img");
var canvas = document.createElement("canvas");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.height;
var ctx = canvas.getContext("2d");
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var texture;
var loader = new THREE.OBJLoader( manager );
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 = 150;
// scene
scene = new THREE.Scene();
var ambientLight = new THREE.AmbientLight( 0xFFFFFF, 0.9 );
scene.add( ambientLight );
var directLight = new THREE.DirectionalLight( 0xFFFFFF, 0.2 );
camera.add( directLight );
scene.add( camera );
controls = new THREE.OrbitControls( camera );
controls.addEventListener( 'change', render );
controls.minPolarAngle = 1.5;
controls.maxPolarAngle = 1.5;
var svgData = (new XMLSerializer()).serializeToString(svg);
img.setAttribute("src", "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(svgData))) );
img.onload = function() {
ctx.drawImage(img, 0, 0);
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
material = new THREE.MeshPhongMaterial({
map: texture
});
material.map.minFilter = THREE.LinearFilter;
};
renderer = new THREE.WebGLRenderer({canvas:garmentOBJ,antialias:true});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
//
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 animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
make the scene object global or bind it to window object like this: window.scene = scene.

Hide objects on Click with raycaster

I wanna hide scene objects with clicking on them,
I read many "raycaster" tutorials but I don't know where is my fault
with these codes when I open my HTML file all the objects are hidden.
I have deleted most of irreverent codes to raycaster.
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = -250;
var container, stats;
var group1 , group2 , group3 ;
var camera, scene, controls;
var renderer;
var mesh;
var textureCube;
var cameraCube, sceneCube;
var loader;
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 and controls
....
// SCENE
scene = new THREE.Scene();
// SKYBOX
.....
//models
group1=...
group2=...
group3=...
cubes = new THREE.Object3D() ;
cubes.add( group1 ) ;
cubes.add( group2 ) ;
cubes.add( group3 ) ;
mouseVector = new THREE.Vector3();
projector = new THREE.Projector();
// LIGHTS
lights...
// RENDERER
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
renderer.domElement.style.position = "relative";
renderer.autoClear = false;
container.appendChild( renderer.domElement );
//
renderer.gammaInput = true;
renderer.gammaOutput = true;
// STATS
stats = new Stats();
container.appendChild( stats.domElement );
// EVENTS
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener( 'mousemove', onDocumentMouseMove, false );
}
//
function onWindowResize( event ) {
....
}
function onDocumentMouseMove(event) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
mouseVector.x = 2 * (e.clientX / containerWidth) - 1;
mouseVector.y = 1 - 2 * ( e.clientY / containerHeight );
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
controls.update();
cameraCube.rotation.copy( camera.rotation );
renderer.clear();
renderer.render( sceneCube, cameraCube );
//raycast
var raycaster = projector.pickingRay( mouseVector.clone(), camera );
window.addEventListener( 'mousedown', onMouseDown, false );
var onMouseDown = function ( event ) {
var intersects = raycaster.intersectObjects( cubes.children );
var intersection = intersects[0] , obj = intersection.object ;
obj.visible = false ;
};
renderer.render( scene, camera );
}
</script>
You are doing the raycast on every frame while rendering. When you want to raycast on mouse clicks, you need an Event Listener:
window.addEventListener( 'mousedown', onMouseDown, false );
var onMouseDown = function ( event ) {
var intersects = raycaster.intersectObjects( cubes.children );
var intersection = intersects[0], obj = intersection.object;
obj.visible = false ;
};

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

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

Categories

Resources