I'm using three.js and have now a scene with a floor and a car as json loaded. Everything fine but the car is just black and not with the texture from blender. Is there any possibility to export it directly with textures from blender or add the textures afterwards ?
Here's the code I use :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>three.js - pointerlock controls</title>
<style>
html, body {
width: 100%;
height: 100%;
}
body {
background-color: #eeeeee;
margin: 0;
overflow: hidden;
font-family: arial;
}
#blocker {
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
}
#instructions {
width: 100%;
height: 100%;
display: -webkit-box;
display: -moz-box;
display: box;
-webkit-box-orient: horizontal;
-moz-box-orient: horizontal;
box-orient: horizontal;
-webkit-box-pack: center;
-moz-box-pack: center;
box-pack: center;
-webkit-box-align: center;
-moz-box-align: center;
box-align: center;
color: #ffffff;
text-align: center;
cursor: pointer;
}
</style>
</head>
<body>
<script src="../build/three.min.js"></script>
<script src="js/controls/PointerLockControls.js"></script>
<div id="blocker">
<div id="instructions">
<span style="font-size:40px">Click to move</span>
<br />
(WASD or Arrow Keys = Move, SPACE = Jump, MOUSE = Look around)
</div>
</div>
<script>
var camera, scene, renderer;
var geometry, material, mesh;
var loader;
var mesh2;
var loadModel;
var controls,time = Date.now();
var objects = [];
var ray;
var blocker = document.getElementById( 'blocker' );
var instructions = document.getElementById( 'instructions' );
// http://www.html5rocks.com/en/tutorials/pointerlock/intro/
var havePointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
if ( havePointerLock ) {
var element = document.body;
var pointerlockchange = function ( event ) {
if ( document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ) {
controls.enabled = true;
blocker.style.display = 'none';
} else {
controls.enabled = false;
blocker.style.display = '-webkit-box';
blocker.style.display = '-moz-box';
blocker.style.display = 'box';
instructions.style.display = '';
}
}
var pointerlockerror = function ( event ) {
instructions.style.display = '';
}
// Hook pointer lock state change events
document.addEventListener( 'pointerlockchange', pointerlockchange, false );
document.addEventListener( 'mozpointerlockchange', pointerlockchange, false );
document.addEventListener( 'webkitpointerlockchange', pointerlockchange, false );
document.addEventListener( 'pointerlockerror', pointerlockerror, false );
document.addEventListener( 'mozpointerlockerror', pointerlockerror, false );
document.addEventListener( 'webkitpointerlockerror', pointerlockerror, false );
instructions.addEventListener( 'click', function ( event ) {
instructions.style.display = 'none';
// Ask the browser to lock the pointer
element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
if ( /Firefox/i.test( navigator.userAgent ) ) {
var fullscreenchange = function ( event ) {
if ( document.fullscreenElement === element || document.mozFullscreenElement === element || document.mozFullScreenElement === element ) {
document.removeEventListener( 'fullscreenchange', fullscreenchange );
document.removeEventListener( 'mozfullscreenchange', fullscreenchange );
element.requestPointerLock();
}
}
document.addEventListener( 'fullscreenchange', fullscreenchange, false );
document.addEventListener( 'mozfullscreenchange', fullscreenchange, false );
element.requestFullscreen = element.requestFullscreen || element.mozRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen;
element.requestFullscreen();
} else {
element.requestPointerLock();
}
}, false );
} else {
instructions.innerHTML = 'Your browser doesn\'t seem to support Pointer Lock API';
}
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 );
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xffffff, 0, 750 );
var light = new THREE.DirectionalLight( 0xffffff, 1.5 );
light.position.set( 1, 1, 1 );
scene.add( light );
var light = new THREE.DirectionalLight( 0xffffff, 0.75 );
light.position.set( -1, - 0.5, -1 );
scene.add( light );
controls = new THREE.PointerLockControls( camera );
scene.add( controls.getObject() );
ray = new THREE.Raycaster();
ray.ray.direction.set( 0, -1, 0 );
// floor
geometry = new THREE.PlaneGeometry( 2000, 2000, 100, 100 );
geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) {
var vertex = geometry.vertices[ i ];
vertex.x += Math.random() * 20 - 10;
vertex.y += Math.random() * 2;
vertex.z += Math.random() * 20 - 10;
}
for ( var i = 0, l = geometry.faces.length; i < l; i ++ ) {
var face = geometry.faces[ i ];
face.vertexColors[ 0 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
face.vertexColors[ 1 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
face.vertexColors[ 2 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
face.vertexColors[ 3 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
}
material = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
// objects
loader = new THREE.JSONLoader( );
loadModel = function(geometry)
{
mesh2 = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { envMap: THREE.ImageUtils.loadTexture( 'textures/metal.jpg', new THREE.SphericalReflectionMapping() ) } ) );
mesh2.scale.set(0.1, 0.1, 0.1);
mesh2.position.set(0, 1, 0);
mesh2.rotation.set(29.85, 3.14, 2);
scene.add( mesh2 );
};
loader.load('blender.js/auto.js', loadModel );
//
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
//
controls.isOnObject( false );
ray.ray.origin.copy( controls.getObject().position );
ray.ray.origin.y -= 10;
var intersections = ray.intersectObjects( objects );
if ( intersections.length > 0 ) {
var distance = intersections[ 0 ].distance;
if ( distance > 0 && distance < 10 ) {
controls.isOnObject( true );
}
}
controls.update( Date.now() - time );
renderer.render( scene, camera );
time = Date.now();
}
</script>
</body>
</html>
The part with //objects is where I load the car I already tried to add some example texture which doesn't work as well. The best would be when I can simply import the textures in blender together with the model.
Tutorial how to export from blender: here
Load object with texture:
var loader = new THREE.JSONLoader();
loader.load( "obj.js", function(geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
mesh = new THREE.Mesh(geometry, materials);
scene.add(mesh)
});
Add texture separately:
var loader = new THREE.JSONLoader();
loader.load( "obj.js", function(geometry) {
var texture = THREE.ImageUtils.loadTexture(textureUrl);
var material = new THREE.MeshLambertMaterial({map: texture});
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh)
});
Related
I have an animation prototype - which plays on scroll - is there a way to reset animation on scroll to top/bottom? Basically from the top it plays and stops when it reaches the bottom? Right now the animation loops and ignores top/bottom (start/end).
When scrolled from the top it plays forward and when reached the bottom it plays in reverse is the desired bahaviour.
var container, stats, controls;
var camera, scene, renderer, light;
var clock = new THREE.Clock();
var mixer = [];
var mixers = [];
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set( 0, 100, 100 );
scene = new THREE.Scene();
light = new THREE.HemisphereLight( 0xffffff, 0x444444 );
light.position.set( 0, 200, 0 );
scene.add( light );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 200, 100 );
light.castShadow = true;
light.shadow.camera.top = 180;
light.shadow.camera.bottom = -100;
light.shadow.camera.left = -120;
light.shadow.camera.right = 120;
scene.add( light );
// scene.add( new THREE.CameraHelper( light.shadow.camera ) );
var grid = new THREE.GridHelper( 2000, 20, 0x000000, 0x000000 );
grid.material.opacity = 0.2;
grid.material.transparent = true;
scene.add( grid );
// model
var loader = new THREE.FBXLoader();
loader.load( 'https://threejs.org/examples/models/fbx/Samba Dancing.fbx', function ( object ) {
object.mixer = new THREE.AnimationMixer( object );
mixers.push( object.mixer );
var action = object.mixer.clipAction( object.animations[ 0 ] );
action.play();
object.traverse( function ( child ) {
if ( child.isMesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
} );
object.position.y = 85;
scene.add( object );
} );
renderer = new THREE.WebGLRenderer( { alpha: true, antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
container.appendChild( renderer.domElement );
window.addEventListener( 'mousewheel', onMouseWheel, false );
window.addEventListener( 'touchstart', onTouchStart, false );
window.addEventListener( 'touchmove', onTouchMove, false );
window.addEventListener('resize', onResize, false);
// stats
stats = new Stats();
container.appendChild( stats.dom );
}
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onMouseWheel( event ) {
if(event.deltaY > 0){
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() * 5 );
}
} else {
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() * -5 );
}
}
}
function onTouchStart(event) {
startY = event.touches[ 0 ].pageY;
}
function onTouchMove( event ) {
var delta = event.deltaY;
if(event.deltaY > 0){
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() * 5 );
}
} else {
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() * -5 );
}
}
}
function animate() {
delta = clock.getDelta();
requestAnimationFrame( animate );
renderer.render( scene, camera );
stats.update();
}
body {
margin: 0px;
overflow: hidden;
}
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejs.org/examples/js/libs/inflate.min.js"></script>
<script src="https://threejs.org/examples/js/loaders/FBXLoader.js"></script>
<script src="https://threejs.org/examples/js/WebGL.js"></script>
<script src="https://threejs.org/examples/js/libs/stats.min.js"></script>
First off you should never link directly to threejs.org. Your example will break when the three.js devs update the version which will make your question example useless to others. Use a specific version from a CDN!
Otherwise if you save off the clips
object.mixer = new THREE.AnimationMixer( object );
mixers.push( object.mixer );
const clip = object.animations[0];
clips.push(clip);
var action = object.mixer.clipAction(clip);
action.play();
Then maybe you could use code like this
function updateAnimation(direction) {
const delta = direction * 5 * clock.getDelta();
for (let i = 0; i < mixers.length; ++i) {
const mixer = mixers[i];
const clip = clips[i];
const duration = clip.duration;
const newTime = THREE.MathUtils.clamp(mixer.time + delta, 0, duration);
mixer.setTime(newTime);
}
}
function onMouseWheel( event ) {
updateAnimation(Math.sign(event.deltaY));
}
...
var container, stats, controls;
var camera, scene, renderer, light;
var duration;
var clock = new THREE.Clock();
var mixer = [];
var mixers = [];
var clips = [];
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set( 0, 100, 100 );
scene = new THREE.Scene();
light = new THREE.HemisphereLight( 0xffffff, 0x444444 );
light.position.set( 0, 200, 0 );
scene.add( light );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 200, 100 );
light.castShadow = true;
light.shadow.camera.top = 180;
light.shadow.camera.bottom = -100;
light.shadow.camera.left = -120;
light.shadow.camera.right = 120;
scene.add( light );
// scene.add( new THREE.CameraHelper( light.shadow.camera ) );
var grid = new THREE.GridHelper( 2000, 20, 0x000000, 0x000000 );
grid.material.opacity = 0.2;
grid.material.transparent = true;
scene.add( grid );
// model
var loader = new THREE.FBXLoader();
loader.load( 'https://threejs.org/examples/models/fbx/Samba Dancing.fbx', function ( object ) {
object.mixer = new THREE.AnimationMixer( object );
mixers.push( object.mixer );
const clip = object.animations[0];
clips.push(clip);
var action = object.mixer.clipAction(clip);
action.play();
object.traverse( function ( child ) {
if ( child.isMesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
} );
object.position.y = 85;
scene.add( object );
} );
renderer = new THREE.WebGLRenderer( { alpha: true, antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
container.appendChild( renderer.domElement );
window.addEventListener( 'mousewheel', onMouseWheel, false );
window.addEventListener('resize', onResize, false);
// stats
stats = new Stats();
container.appendChild( stats.dom );
}
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function updateAnimation(direction) {
const delta = direction * 5 * clock.getDelta();
for (let i = 0; i < mixers.length; ++i) {
const mixer = mixers[i];
const clip = clips[i];
const duration = clip.duration;
const newTime = THREE.MathUtils.clamp(mixer.time + delta, 0, duration);
mixer.setTime(newTime);
}
}
function onMouseWheel( event ) {
updateAnimation(Math.sign(event.deltaY));
}
function animate() {
delta = clock.getDelta();
requestAnimationFrame( animate );
renderer.render( scene, camera );
stats.update();
}
body {
margin: 0px;
overflow: hidden;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/libs/inflate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/loaders/FBXLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/WebGL.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/libs/stats.min.js"></script>
I am trying to display my ply modifying three.js webgl_loader_ply example, but it is not showing anything. I can see the object when I open the ply with MeshLab. I have tried to zoom out, change the camera angle, disable the shadowedlight to no avail. Any more tips?
Below is the edited webgl_loader_ply.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - PLY</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;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display:block;
}
a { color: skyblue }
.button { background:#999; color:#eee; padding:0.2em 0.5em; cursor:pointer }
.highlight { background:orange; color:#fff; }
span {
display: inline-block;
width: 60px;
float: left;
text-align: center;
}
</style>
</head>
<body>
<div id="info">
three.js -
PLY loader test by Wei Meng. Image from John Burkardt
</div>
<script src="../build/three.js"></script>
<script src="js/loaders/PLYLoader.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, cameraTarget, scene, renderer;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 1, 15 );
camera.position.set( 3, 0.15, 3 );
cameraTarget = new THREE.Vector3( 0, -0.1, 0 );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x72645b );
scene.fog = new THREE.Fog( 0x72645b, 2, 15 );
// Ground
var plane = new THREE.Mesh(
new THREE.PlaneBufferGeometry( 40, 40 ),
new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } )
);
plane.rotation.x = -Math.PI/2;
plane.position.y = -0.5;
scene.add( plane );
plane.receiveShadow = true;
// PLY file
var loader = new THREE.PLYLoader();
loader.load( './models/ply/binary/foot.ply', function ( geometry ) {
geometry.computeVertexNormals();
var material = new THREE.MeshStandardMaterial( { color: 0x0055ff, flatShading: true } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.y = - 0.2;
mesh.position.z = 0.3;
mesh.rotation.x = - Math.PI / 2;
mesh.scale.multiplyScalar( 0.001 );
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add( mesh );
} );
// Lights
scene.add( new THREE.HemisphereLight( 0x443333, 0x111122 ) );
addShadowedLight( 1, 1, 1, 0xffffff, 1.35 );
addShadowedLight( 0.5, 1, -1, 0xffaa00, 1 );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMap.enabled = true;
renderer.shadowMap.renderReverseSided = false;
container.appendChild( renderer.domElement );
// stats
stats = new Stats();
container.appendChild( stats.dom );
// resize
window.addEventListener( 'resize', onWindowResize, false );
}
function addShadowedLight( x, y, z, color, intensity ) {
var directionalLight = new THREE.DirectionalLight( color, intensity );
directionalLight.position.set( x, y, z );
scene.add( directionalLight );
directionalLight.castShadow = true;
var d = 1;
directionalLight.shadow.camera.left = -d;
directionalLight.shadow.camera.right = d;
directionalLight.shadow.camera.top = d;
directionalLight.shadow.camera.bottom = -d;
directionalLight.shadow.camera.near = 1;
directionalLight.shadow.camera.far = 4;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.bias = -0.005;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
var timer = Date.now() * 0.0005;
camera.position.x = Math.sin( timer ) * 2.5;
camera.position.z = Math.cos( timer ) * 2.5;
camera.lookAt( cameraTarget );
renderer.render( scene, camera );
}
</script>
</body>
</html>
You will see it if you comment out the lines
mesh.rotation.x = - Math.PI / 2;
mesh.scale.multiplyScalar( 0.001 );
This is a little modified version of "three.js webgl cameras." (got from examples)
I have created a wrapper div for the future canvas and a 'three_webgl' instance.
(I create an instance for a new three_webgl, which is the original function instanced as an object).
As you can see there are two buttons one to create the instance and the animation and the other to stop the animation and delete the instance.
I have a 'stop' control inside the animate loop.
Also I have increased the number of points for the pointcloud (100 000) to measure the memory spent.
The problem I have is that delete works fine but I leave 10 000 KB 'lost'
You can play with create-start / stop- delete and you can see how the memory grows and grows.
My question is how to delete the three environment and data correctly. The goal is to avoid memory leaks.
I'm using the dev branch dated on 12 / 05, chrome 34.0 and Windows XP.
This is the code. (Maybe it is neccesary to change the tree paths for three and stats.)
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - cameras</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: #808080;
font-family:Monospace;
font-size:13px;
text-align:center;
background-color: #000;
margin: 0px;
overflow: hidden;
}
#info {
position: absolute;
top: 0px; width: 100%;
padding: 5px;
z-index: 100;
}
a {
color: #0080ff;
}
b { color: lightgreen }
#stats { position: absolute; top:0; left: 0 }
#stats #fps { background: transparent !important }
#stats #fps #fpsText { color: #777 !important }
#stats #fps #fpsGraph { display: none }
#apDiv1 {
position: absolute;
width: 652px;
height: 376px;
z-index: 101;
left: 54px;
top: 95px;
border: 1px solid white;
}
#apDiv2 {
position: absolute;
width: 655px;
height: 80px;
z-index: 102;
left: 53px;
top: 490px;
border: 1px red solid;
}
#apDiv3 {
position: absolute;
width: 200px;
height: 34px;
z-index: 103;
left: 54px;
top: 52px;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">three.js - cameras<br/>
<b>O</b> orthographic <b>P</b> perspective
</div>
<div id="apDiv1"></div>
<div id="apDiv2"></div>
<div id="apDiv3">
<input type="submit" name="b1" id="b1" value="crete-start" onClick="new_webgl()">
<input type="submit" name="b2" id="b2" value="stop-delete" onClick="del_webgl()">
</div>
<script src="tree/build/three.js"></script>
<script src="tree/examples/js/libs/stats.min.js"></script>
<script>
var webgl_true;
try
{ var canvas = document.createElement( 'canvas' );
webgl_true = !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); }
catch( e ) { webgl_true= false; }
THE_DIV2 = document.getElementById("apDiv2");
THE_DIV2.innerHTML = "Webgl detector : "+webgl_true;
</script>
<script>
var webgl;
var renderer;
var del_renderer = false;
new_webgl = function () { webgl = new three_webgl(); }
var del_webgl = function () { del_renderer = true;
THE_DIV.parentNode.removeChild(THE_DIV);
webgl = null;
// THE_DIV.appendChild( renderer.domElement );
}
three_webgl = function () {
del_renderer = false;
THE_DIV = document.createElement( 'div' );
THE_DIV.style.height="100%";
document.getElementById("apDiv1").appendChild(THE_DIV);
var SCREEN_WIDTH = THE_DIV.clientWidth;
var SCREEN_HEIGHT = THE_DIV.clientHeight;
var container, stats;
var camera, scene, mesh;
var cameraRig, activeCamera, activeHelper;
var cameraPerspective, cameraOrtho;
var cameraPerspectiveHelper, cameraOrthoHelper;
init();
animate();
function init () {
//container = document.createElement( 'div' );
//document.body.appendChild( container );
scene = new THREE.Scene();
//
camera = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 );
camera.position.z = 2500;
cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 150, 1000 );
cameraPerspectiveHelper = new THREE.CameraHelper( cameraPerspective );
scene.add( cameraPerspectiveHelper );
//
cameraOrtho = new THREE.OrthographicCamera( 0.5 * SCREEN_WIDTH / - 2, 0.5 * SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, 150, 1000 );
cameraOrthoHelper = new THREE.CameraHelper( cameraOrtho );
scene.add( cameraOrthoHelper );
//
activeCamera = cameraPerspective;
activeHelper = cameraPerspectiveHelper;
// counteract different front orientation of cameras vs rig
cameraOrtho.rotation.y = Math.PI;
cameraPerspective.rotation.y = Math.PI;
cameraRig = new THREE.Object3D();
cameraRig.add( cameraPerspective );
cameraRig.add( cameraOrtho );
scene.add( cameraRig );
//
mesh = new THREE.Mesh( new THREE.SphereGeometry( 100, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true } ) );
scene.add( mesh );
var mesh2 = new THREE.Mesh( new THREE.SphereGeometry( 50, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x00ff00, wireframe: true } ) );
mesh2.position.y = 150;
mesh.add( mesh2 );
var mesh3 = new THREE.Mesh( new THREE.SphereGeometry( 5, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x0000ff, wireframe: true } ) );
mesh3.position.z = 150;
cameraRig.add( mesh3 );
//
var geometry = new THREE.Geometry();
for ( var i = 0; i < 100000; i ++ ) {
var vertex = new THREE.Vector3();
vertex.x = THREE.Math.randFloatSpread( 2000 );
vertex.y = THREE.Math.randFloatSpread( 2000 );
vertex.z = THREE.Math.randFloatSpread( 2000 );
geometry.vertices.push( vertex );
}
var particles = new THREE.PointCloud( geometry, new THREE.PointCloudMaterial( { color: 0x888888 } ) );
scene.add( particles );
//
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
renderer.domElement.style.position = "relative";
THE_DIV.appendChild( renderer.domElement );
renderer.autoClear = false;
//
stats = new Stats();
THE_DIV2.appendChild( stats.domElement );
//
window.addEventListener( 'resize', onWindowResize, false );
document.addEventListener( 'keydown', onKeyDown, false );
}
//
function onKeyDown ( event ) {
switch( event.keyCode ) {
case 79: /*O*/
activeCamera = cameraOrtho;
activeHelper = cameraOrthoHelper;
break;
case 80: /*P*/
activeCamera = cameraPerspective;
activeHelper = cameraPerspectiveHelper;
break;
}
};
//
function onWindowResize( event ) {
SCREEN_WIDTH = window.innerWidth;
SCREEN_HEIGHT = window.innerHeight;
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
camera.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT;
camera.updateProjectionMatrix();
cameraPerspective.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT;
cameraPerspective.updateProjectionMatrix();
cameraOrtho.left = - 0.5 * SCREEN_WIDTH / 2;
cameraOrtho.right = 0.5 * SCREEN_WIDTH / 2;
cameraOrtho.top = SCREEN_HEIGHT / 2;
cameraOrtho.bottom = - SCREEN_HEIGHT / 2;
cameraOrtho.updateProjectionMatrix();
}
//
function animate() {
if (!(del_renderer))
{ requestAnimationFrame( animate );
render();
}
stats.update();
if (del_renderer) {renderer=null;}
}
function render() {
var r = Date.now() * 0.0005;
mesh.position.x = 700 * Math.cos( r );
mesh.position.z = 700 * Math.sin( r );
mesh.position.y = 700 * Math.sin( r );
mesh.children[ 0 ].position.x = 70 * Math.cos( 2 * r );
mesh.children[ 0 ].position.z = 70 * Math.sin( r );
if ( activeCamera === cameraPerspective ) {
cameraPerspective.fov = 35 + 30 * Math.sin( 0.5 * r );
cameraPerspective.far = mesh.position.length();
cameraPerspective.updateProjectionMatrix();
cameraPerspectiveHelper.update();
cameraPerspectiveHelper.visible = true;
cameraOrthoHelper.visible = false;
} else {
cameraOrtho.far = mesh.position.length();
cameraOrtho.updateProjectionMatrix();
cameraOrthoHelper.update();
cameraOrthoHelper.visible = true;
cameraPerspectiveHelper.visible = false;
}
cameraRig.lookAt( mesh.position );
renderer.clear();
activeHelper.visible = false;
renderer.setViewport( 0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT );
renderer.render( scene, activeCamera );
activeHelper.visible = true;
renderer.setViewport( SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT );
renderer.render( scene, camera );
}
}
</script>
</body>
</html>
I modified an example from Three.js library and I tried to add click event on objects.
After a lot of attempts... I'm still not capable to listening for clicks.
This code produces convex forms.
There is my code:
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, scene, renderer;
var objects = [];
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.y = 400;
scene = new THREE.Scene();
var light, object, object2, materials;
scene.add( new THREE.AmbientLight( 0x404040 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 1, 0 );
scene.add( light );
var map = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' );
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;
materials = [
new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map } ),
new THREE.MeshBasicMaterial( { color: 0x242424, wireframe: true, transparent: false, opacity: 0.1 } )
];
// random convex
points = [];
for ( var i = 0; i < 15; i ++ ) {
points.push( randomPointInSphere( 50 ) );
}
object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials );
object.position.set( -250, 0, 200 );
scene.add( object );
objects.push( object );
object.callback = function() { console.log('blabla');}
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
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 );
}
function randomPointInSphere( radius ) {
return new THREE.Vector3(
( Math.random() - 0.5 ) * 1 * radius,
( Math.random() - 0.5 ) * 1 * radius,
( Math.random() - 0.5 ) * 1 * radius
);
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
var timer = Date.now() * 0.0001;
camera.position.x = Math.cos( timer ) * 800;
camera.position.z = Math.sin( timer ) * 800;
camera.lookAt( scene.position );
for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
var object = scene.children[ i ];
object.rotation.x = timer * 5;
object.rotation.y = timer * 2.5;
}
renderer.render( scene, camera );
}
function addMeteor()
{
var map = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' );
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;
var materials = [
new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map } ),
new THREE.MeshBasicMaterial( { color: 0x242424, wireframe: true, transparent: false, opacity: 0.1 } )
];
objects.push( materials );
var object3;
var points3 = [];
for ( var i = 0; i < 10; i ++ ) {
points3.push( randomPointInSphere( 50 ) );
}
object3 = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points3 ), materials );
object3.position.set( -50, Math.floor((Math.random()*window.innerWidth)), Math.floor((Math.random()* window.innerHeight)) );
scene.add( object3 );
objects.push( object3 );
}
projector = new THREE.Projector();
// listeners
document.addEventListener( 'mousedown', onDocumentMouseDown, false)
// keyboard handler
function onDocumentMouseDown( event ) {
event.preventDefault();
console.log('blabla');
var vector = new THREE.Vector3(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
0.5 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
console.log(objects);
var intersects = ray.intersectObjects( objects );
console.log(intersects);
if ( intersects.length > 0 ) {
intersects[0].object.callback();
console.log('blabla');
}
}
renderer.render( scene, camera );
I was supposed to push Mesh into Objects array, but which one?
THREE.SceneUtils.createMultiMaterialObject() creates an object with two child meshes.
So, you need to set the recursive flag to true when calling Raycaster.intersectObjects().
var intersects = ray.intersectObjects( objects, true );
three.js r.62
I've created a scene with textured and meshed cylinder and a grid with line and vertices of three.js. The cylinder has a spinning effect by dragging mouse left or right.
<!DOCTYPE html>
<html lang="en">
<head>
<title>3d Model using HTML5 and three.js</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="three.min.js" type="text/javascript"></script>
<script src="Stats.js" type="text/javascript"></script>
<script src="Detector.js" type="text/javascript"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, scene, renderer, light, projector;
var particleMaterial;
var cylinder, line, geometry, geometry1;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var objects = [];
var radious = 1600, theta = 45, onMouseDownTheta = 45, phi = 60, onMouseDownPhi = 60, isShiftDown = false;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
var info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'Drag to spin the cylinder<br/>Objective: By spining left, cylinder should go into the surface and by spining right it should come out.';
container.appendChild( info );
// camera
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.y = 200;
camera.position.z = 800;
// scene
scene = new THREE.Scene();
// light
scene.add( new THREE.AmbientLight( 0x404040 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 1, 0 );
scene.add( light );
// texture
var materials = [];
for ( var i = 0; i < 6; i ++ ) {
materials.push( new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) );
}//alert(materials.length);
// Grid
geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vector3( - 500, 0, 0 ) );
geometry.vertices.push( new THREE.Vector3( 500, 0, 0 ) );
for ( var i = 0; i <= 20; i ++ ) {
line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ) );
line.position.z = ( i * 50 ) - 500;
scene.add( line );
line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ) );
line.position.x = ( i * 50 ) - 500;
line.rotation.y = 90 * Math.PI / 180;
scene.add( line );
}
// cylinder
geometry1 = new THREE.CylinderGeometry(100, 100, 300, 16, 4, false);
cylinder = new THREE.Mesh(geometry1 ,new THREE.MeshLambertMaterial( { color: 0x2D303D, wireframe: true, shading: THREE.FlatShading } ));
//cylinder.position.x = 100;
cylinder.position.y = -50;
//cylinder.overdraw = true;
scene.add(cylinder);
alert(geometry1.faces.length);
objects.push(cylinder);
// projector
projector = new THREE.Projector();
// renderer
renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
// stats
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.left = window.innerWidth / - 2;
camera.right = window.innerWidth / 2;
camera.top = window.innerHeight / 2;
camera.bottom = window.innerHeight / - 2;
camera.aspect = window.innerWidth / window.innerHeight;
//camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseDown( event ) {
event.preventDefault();
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'mouseup', onDocumentMouseUp, false );
document.addEventListener( 'mouseout', onDocumentMouseOut, false );
mouseXOnMouseDown = event.clientX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
}
function onDocumentMouseMove( event ) {
mouseX = event.clientX - windowHalfX;
targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02;
}
function onDocumentMouseUp( event ) {
document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
document.removeEventListener( 'mouseup', onDocumentMouseUp, false );
document.removeEventListener( 'mouseout', onDocumentMouseOut, false );
}
function onDocumentMouseOut( event ) {
document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
document.removeEventListener( 'mouseup', onDocumentMouseUp, false );
document.removeEventListener( 'mouseout', onDocumentMouseOut, false );
}
function onDocumentTouchStart( event ) {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
}
}
function onDocumentTouchMove( event ) {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - windowHalfX;
targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05;
}
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
cylinder.rotation.y += ( targetRotation - cylinder.rotation.y ) * 0.05;
renderer.render( scene, camera );
}
</script>
</body>
</html>
How do I know which face of cylinder is selected by clicking on a face of it ?
You have to shoot a virtual ray from your viewpoint to the cube. You can then read out the face or faceIndex from the intersected object.
function onDocumentMouseDown( event ) {
event.preventDefault();
// position of mouse + screen calc
var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
projector.unprojectVector( vector, camera );
// create a ray from the camera thru the vector
var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
// array of intersecting object (front to back)
var intersects = ray.intersectObjects( objects );
// are we hitting something?
if ( intersects.length > 0 ) {
// first intersection should be the object (Mesh,...)
console.log(intersects[0].object);
// gimme face as THREE.Face3/4 object
console.log(intersects[0].face);
// tell me face index (int)
console.log(intersects[0].faceIndex);
// lets change color of the intersected object for fun
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
}
}
Also check out the canvas_interactive_cubes example