three.js - zoom in/out complete tube geometry - javascript

I've created a tube geometry with data of 200 points loaded from external javascript file in JSON format. Please find the below code.
<!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>
<input type="button" value="plot" onClick="return plotPath();" />
<script src="three.min.js" type="text/javascript"></script>
<script src="Curve.js" type="text/javascript"></script>
<script src="TubeGeometry.js" type="text/javascript"></script>
<script src="Stats.js" type="text/javascript"></script>
<script src="Detector.js" type="text/javascript"></script>
<script src="path.js" type="text/javascript"></script>
<script>
// variables
var container, stats;
var camera, scene, renderer, controls, stats;
var text, plane, tube, tubeMesh, parent;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var radius = 600;
var theta = 0;
var PI2 = Math.PI * 2;
function plotPath()
{
var obj = getPath();
var segments = 50;
var closed = false;
var debug = true;
var radiusSegments = 12;
var tube;
var points = [];
var x=0,y=0,z=0;
for(var i=0; i<obj.path.length; i++)
{
console.log(obj.path[i].point);
points.push(obj.path[i].point);
extrudePath = new THREE.SplineCurve3(points);
extrudePath.dynamic = true;
tube = new THREE.TubeGeometry(extrudePath, segments, 2, radiusSegments, closed, debug);
tube.dynamic = true;
tubeMesh = new THREE.Mesh(tube ,new THREE.MeshBasicMaterial({
color: 0x000000, side: THREE.DoubleSide,
opacity: 0.5, transparent: true, wireframe: true}));
tubeMesh.__dirtyVertices = true;
tubeMesh.dynamic = true;
parent = new THREE.Object3D();
parent.position.y = 100;
if ( tube.debug ) tubeMesh.add( tube.debug );
parent.add( tubeMesh );
}
scene.add( tubeMesh );
scene.add(parent);
animate();
}
init();
function init(){
// container
container = document.createElement( 'div' );
document.body.appendChild( container );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColorHex(0xEEEEEE, 1.0);
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.clear();
container.appendChild( renderer.domElement );
// camera
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set(-100,75,75);
// scene
scene = new THREE.Scene();
camera.lookAt(scene.position);
// light
scene.add( new THREE.AmbientLight( 0x404040 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 1, 0 );
scene.add( light );
// CONTROLS
controls = new THREE.TrackballControls( camera );
// 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 );
}
// projector
projector = new THREE.Projector();
plotPath();
// 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( 'mouseover', onDocumentMouseOver, false );
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
window.addEventListener('DOMMouseScroll', mousewheel, false);
window.addEventListener('mousewheel', mousewheel, false);
window.addEventListener( 'resize', onWindowResize, false );
}
function mousewheel(event) {
var fovMAX = 160;
var fovMIN = 1;
camera.fov -= event.wheelDeltaY * 0.05;
camera.fov = Math.max( Math.min( camera.fov, fovMAX ), fovMIN );
camera.projectionMatrix = new THREE.Matrix4().makePerspective(camera.fov, window.innerWidth / window.innerHeight, camera.near, camera.far);
}
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;
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 onDocumentMouseOver( 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, renderer.domElement );
render();
update();
}
function update(){
controls.update();
}
function toCameraCoords(position) {
return camera.matrixWorldInverse.multiplyVector3(position.clone());
}
function render() {
tubeMesh.rotation.y += ( targetRotation - tubeMesh.rotation.y ) * 0.15;
camera.lookAt(scene.position);
camera.updateMatrixWorld();
renderer.render( scene, camera );
}
</script>
</body>
</html>
When I use mouse wheel to zoom in, the camera will zoom in at starting point of the tube. How do I make the tube geometry can be zoomed completely or in other words any part of the tube can be zoomed ?

As with any conventional real life camera, you can change the focal length (zoom) of THREE.PerspectiveCamera by calling setLens method. I find this way very intuitive and much simplier than moving the camera to zoom in/out.
Here is the method docs in three.js:
/**
* Uses Focal Length (in mm) to estimate and set FOV
* 35mm (fullframe) camera is used if frame size is not specified;
* Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
*/
THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight )
...
And here is an example usage:
var focalLength = 25.734; // equivalent to FOV=50
$('#scene').mousewheel(function (event, delta, deltaX, deltaY) {
event.preventDefault();
focalLength += deltaY;
camera.setLens(focalLength);
});
The method jQuery.fn.mousewheel is provided by Mousewheel Plugin.

document.body.addEventListener( 'mousewheel', mousewheel, false );
document.body.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox
function mousewheel( e ) {
var d = ((typeof e.wheelDelta != "undefined")?(-e.wheelDelta):e.detail);
d = 100 * ((d>0)?1:-1);
var cPos = camera.position;
if (isNaN(cPos.x) || isNaN(cPos.y) || isNaN(cPos.y))
return;
var r = cPos.x*cPos.x + cPos.y*cPos.y;
var sqr = Math.sqrt(r);
var sqrZ = Math.sqrt(cPos.z*cPos.z + r);
var nx = cPos.x + ((r==0)?0:(d * cPos.x/sqr));
var ny = cPos.y + ((r==0)?0:(d * cPos.y/sqr));
var nz = cPos.z + ((sqrZ==0)?0:(d * cPos.z/sqrZ));
if (isNaN(nx) || isNaN(ny) || isNaN(nz))
return;
cPos.x = nx;
cPos.y = ny;
cPos.z = nz;
}
or even simpler ajusting only the camera :
var mousewheel = function ( e ) {
var d = ((typeof e.wheelDelta != "undefined")?(-e.wheelDelta):e.detail);
d = 100 * ((d>0)?1:-1);
var cPos = camera.position;
if (isNaN(cPos.x) || isNaN(cPos.y) || isNaN(cPos.y)) return;
// Your zomm limitation
// For X axe you can add anothers limits for Y / Z axes
if (cPos.x > _YOUR_ZOOM_MIN_X_ || cPos.x < _YOUR_ZOOM_MAX_X_ ){
return ;
}
mb = d>0 ? 1.1 : 0.9;
cPos.x = cPos.x * mb;
cPos.y = cPos.y * mb;
cPos.z = cPos.z * mb;
}

Related

How to drag and rotate multiple objects using Three.js

In order to find the best relative position for each object, if I want to move, rotate multiple objects like 10 objects by clicking and dragging objects using Three.js, are there any other efficient ways to do that? I found the real example ((https://codepen.io/OpherV/pen/YXwwNR). However, it seems good for just 1 or 2 objects. Could you please advise any examples or solutions using Three.js?
Thanks a lot.
/**
* Provides requestAnimationFrame in a cross browser way.
* #author paulirish / http://paulirish.com/
*/
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
}
var container, stats;
var camera, scene, renderer;
var cube, plane;
var targetRotationX = 0.5;
var targetRotationOnMouseDownX = 0;
var targetRotationY = 0.2;
var targetRotationOnMouseDownY = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var mouseY = 0;
var mouseYOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var slowingFactor = 0.25;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.y = 150;
camera.position.z = 500;
scene.add( camera );
var materials = [];
for ( var i = 0; i < 6; i ++ ) {
materials.push( new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) );
}
cube = new THREE.Mesh( new THREE.BoxGeometry( 200, 200, 200 ) , new THREE.MeshFaceMaterial(materials) );
cube.position.y = 150;
cube.overdraw = true;
scene.add( cube );
plane = new THREE.Mesh( new THREE.PlaneGeometry( 200, 200 ), new THREE.MeshBasicMaterial( { color: 0xe0e0e0 } ) );
plane.rotation.x = - 90 * ( Math.PI / 180 );
plane.overdraw = true;
renderer = new THREE.WebGLRenderer();
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 );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
}
function onDocumentMouseDown( event ) {
event.preventDefault();
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'mouseup', onDocumentMouseUp, false );
document.addEventListener( 'mouseout', onDocumentMouseOut, false );
mouseXOnMouseDown = event.clientX - windowHalfX;
targetRotationOnMouseDownX = targetRotationX;
mouseYOnMouseDown = event.clientY - windowHalfY;
targetRotationOnMouseDownY = targetRotationY;
}
function onDocumentMouseMove( event ) {
mouseX = event.clientX - windowHalfX;
targetRotationX = ( mouseX - mouseXOnMouseDown ) * 0.00025;
mouseY = event.clientY - windowHalfY;
targetRotationY = ( mouseY - mouseYOnMouseDown ) * 0.00025;
}
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 animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
rotateAroundWorldAxis(cube, new THREE.Vector3(0, 1, 0), targetRotationX);
rotateAroundWorldAxis(cube, new THREE.Vector3(1, 0, 0), targetRotationY);
targetRotationY = targetRotationY * (1 - slowingFactor);
targetRotationX = targetRotationX * (1 - slowingFactor);
renderer.render( scene, camera );
}
function rotateAroundObjectAxis(object, axis, radians) {
var rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationAxis(axis.normalize(), radians);
object.matrix.multiply(rotationMatrix);
object.rotation.setFromRotationMatrix( object.matrix );
}
function rotateAroundWorldAxis( object, axis, radians ) {
var rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationAxis( axis.normalize(), radians );
rotationMatrix.multiply( object.matrix ); // pre-multiply
object.matrix = rotationMatrix;
object.rotation.setFromRotationMatrix( object.matrix );
}
body {
font-family: Monospace;
background-color: #f0f0f0;
margin: 0px;
overflow: hidden;
}
.caption{
padding: 1rem;
color: white;
background: black;
font-size: 2rem;
text-align:center;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Object drag rotation in Three.js</title>
<link rel="stylesheet" href="./style.css">
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/loaders/OBJLoader.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/stats.js/r11/Stats.min.js'></script>
</head>
<body>
<!-- partial:index.partial.html -->
<div class="caption">Drag to rotate</div>
<!-- partial -->
</body>
<script src="./script.js"></script>
</html>

Position camera inside three.js cube

I'm starting learning three.js. I studied the Getting started section on the website and had a look to some examples, but I can't figure out many things.
What I'd like to do is to create a cube (a box) and put the camera in the middle of it, so that I would see the inner side of each face. Is this actually possible?
Looking at the documentation, various examples and on stackoverflow, right now I'm at this point:
var camera, scene, renderer;
var isUserInteracting = false,
onMouseDownMouseX = 0, onMouseDownMouseY = 0,
lon = 0, onMouseDownLon = 0,
lat = 0, onMouseDownLat = 0,
phi = 0, theta = 0;
init();
animate();
function init() {
var container, mesh;
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1100 );
camera.target = new THREE.Vector3(1, 1, 1);
scene = new THREE.Scene();
var geometry = new THREE.BoxGeometry(7, 7, 7);
geometry.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
var material = [
new THREE.MeshBasicMaterial( { color: 0x8bf2a7 } ),
new THREE.MeshBasicMaterial( { color: 0x1ad9a5 } ),
new THREE.MeshBasicMaterial( { color: 0xdadcad } ),
new THREE.MeshBasicMaterial( { color: 0xb1b1b1 } ),
new THREE.MeshBasicMaterial( { color: 0x3a3a3a } ), // front
new THREE.MeshBasicMaterial( { color: 0xf5f5f5 } )
];
mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial(material) );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'mouseup', onDocumentMouseUp, false );
document.addEventListener( 'dragover', function ( event ) {
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
}, false );
document.addEventListener( 'dragenter', function ( event ) {
document.body.style.opacity = 0.5;
}, false );
document.addEventListener( 'dragleave', function ( event ) {
document.body.style.opacity = 1;
}, false );
document.addEventListener( 'drop', function ( event ) {
event.preventDefault();
var reader = new FileReader();
reader.addEventListener( 'load', function ( event ) {
material.map.image.src = event.target.result;
material.map.needsUpdate = true;
}, false );
reader.readAsDataURL( event.dataTransfer.files[ 0 ] );
document.body.style.opacity = 1;
}, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseDown( event ) {
event.preventDefault();
isUserInteracting = true;
onPointerDownPointerX = event.clientX;
onPointerDownPointerY = event.clientY;
onPointerDownLon = lon;
onPointerDownLat = lat;
}
function onDocumentMouseMove( event ) {
if ( isUserInteracting === true ) {
lon = ( onPointerDownPointerX - event.clientX ) * 0.1 + onPointerDownLon;
lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
}
}
function onDocumentMouseUp( event ) {
isUserInteracting = false;
}
function onDocumentMouseWheel( event ) {
// WebKit
if ( event.wheelDeltaY ) {
camera.fov -= event.wheelDeltaY * 0.05;
// Opera / Explorer 9
} else if ( event.wheelDelta ) {
camera.fov -= event.wheelDelta * 0.05;
// Firefox
} else if ( event.detail ) {
camera.fov += event.detail * 1.0;
}
camera.updateProjectionMatrix();
}
function animate() {
requestAnimationFrame( animate );
update();
}
function update() {
if ( isUserInteracting === false ) {
// lon += 0.1;
}
lat = Math.max( - 85, Math.min( 85, lat ) );
phi = THREE.Math.degToRad( 90 - lat );
theta = THREE.Math.degToRad( lon );
camera.target.x = 500 * Math.sin( phi ) * Math.cos( theta );
camera.target.y = 500 * Math.cos( phi );
camera.target.z = 500 * Math.sin( phi ) * Math.sin( theta );
camera.lookAt( camera.target );
camera.position.z = 3;
/*
// distortion
camera.position.copy( camera.target ).negate();
*/
renderer.render( scene, camera );
}
I can actually see the cube from the inside, but it's not exactly what I want. I'm trying to put the camera in the exact center of the room and I would it to rotate on itself, but I don't exactly how to precisely move it.
If you look at this fiddle the only difference is the material.
Comment and uncomment the following line to see the effect.
THREE.ImageUtils.crossOrigin = '';
Also you can read more at this issue

three.js - disabled textboxes

HTML textboxes are disabled for input. "render" button is working properly and onClick display the defined geometry. I tried by changing render.domElement to different elements on page such as container, info, parent and scene. But could not find out why textboxes are disabled ?
<!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="Curve.js" type="text/javascript"></script>
<script src="TubeGeometry.js" type="text/javascript"></script>
<script src="Stats.js" type="text/javascript"></script>
<script src="Detector.js" type="text/javascript"></script>
<script>
// variables
var container, stats;
var camera, scene, renderer, splineCamera, cameraHelper, cameraEye;
var text, plane, tube, tubeMesh, parent;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var binormal = new THREE.Vector3();
var normal = new THREE.Vector3();
var materials = [];var points = [];
init();
//animate();
function init(){
// HTML form
form = document.createElement( 'div' );
form.innerHTML = 'X: <input type="text" id="txtX" /> Y: <input type="text" id="txtY" /> Z: <input type="text" id="txtZ" /> ';
form.innerHTML += '<input type="button" value="plot" onClick="draw(txtX.value,txtY.value,txtZ.value);" />';
form.innerHTML += '<input type="button" value="render" onClick="animate();" />';
document.body.appendChild( form );
// container
container = document.createElement( 'div' );
document.body.appendChild( container );
// info div
info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
container.appendChild( info );
// camera
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set(30,10,10);
//camera.up = new THREE.Vector3( 0, 1, 1 );
// scene
scene = new THREE.Scene();
camera.lookAt(scene.position);
// light
scene.add( new THREE.AmbientLight( 0x404040 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 1, 0 );
scene.add( light );
// 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 );
}
// extrudePath, Helix Curve
/*var cords = new Array();
cords[0] = new Array(0, 10, 10);
cords[1] = new Array(10, 0, 10);
cords[2] = new Array(10, 0, 0);*/
//extrudePath = new THREE.SplineCurve3([new THREE.Vector3(cords[0]),new THREE.Vector3(cords[1])]);
/*extrudePath = new THREE.SplineCurve3([
new THREE.Vector3(0, 10, 10),
new THREE.Vector3(10, 0, 10),
new THREE.Vector3(10, 0, 0)
]);*/
draw(0,10,10);
draw(10,0,10);
draw(10,0,0);
extrudePath = new THREE.SplineCurve3(points);
console.log(extrudePath);
// Tube Geometry
var segments = 50;
var closed = false;
var debug = true;
var radiusSegments = 12;
//alert('hello');
var tube = new THREE.TubeGeometry(extrudePath, segments, 2, radiusSegments, closed, debug);
// Tube Mesh
/*tubeMesh = THREE.SceneUtils.createMultiMaterialObject( tube, [
new THREE.MeshLambertMaterial({
color: 0xff00ff,
opacity: tube.debug ? 0.2 : 0.8,
transparent: true
}),
new THREE.MeshBasicMaterial({
color: 0x000000,
opacity: 0.5,
wireframe: true
})]);*/
/*for ( var i = 0; i < 6; i ++ ) {
materials.push( new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) );
}
tube.materials = materials;*/
tubeMesh = new THREE.Mesh(tube ,new THREE.MeshBasicMaterial({
color: 0x000000,side: THREE.DoubleSide,
opacity: 0.5,transparent: true,
wireframe: true}));
//tubeMesh = new THREE.Mesh( tube, new THREE.MeshFaceMaterial() );
//THREE.ColorUtils.adjustHSV( tubeMesh.material.color, 0.1, -0.1, 0 );
parent = new THREE.Object3D();
parent.position.y = 100;
if ( tube.debug ) tubeMesh.add( tube.debug );
parent.add( tubeMesh );
scene.add( tubeMesh );
// projector
projector = new THREE.Projector();
// renderer
//renderer = new THREE.CanvasRenderer();
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
// CONTROLS
console.log(renderer.domElement);
controls = new THREE.TrackballControls( this.camera, info );
// 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( 'mouseover', onDocumentMouseOver, false );
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
window.addEventListener( 'resize', onWindowResize, false );
}
function draw(x,y,z)
{
points.push( new THREE.Vector3(x,y,z));
}
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 onDocumentMouseOver( 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() {
tubeMesh.rotation.y += ( targetRotation - tubeMesh.rotation.y ) * 0.15;
camera.updateMatrixWorld();
renderer.render( scene, camera );
requestAnimationFrame( animate );
//render();
update();
}
function update()
{
controls.update();
stats.update();
}
function render() {
tubeMesh.rotation.y += ( targetRotation - tubeMesh.rotation.y ) * 0.15;
camera.updateMatrixWorld();
renderer.render( scene, camera );
}
</script>
</body>
</html>
because of the trackball controls, it's preventing default actions on every mouseinput.
this is a possible duplicate of
Three.JS -- conflict Camera controls with a textbox in a scene
LATE but this works for me. You should enable the mousedown Listener:
FROM:
document.addEventListener( 'mousedown', onDocumentMouseDown, false);
TO:
document.addEventListener( 'mousedown', onDocumentMouseDown, true);

three.js - Uncaught TypeError: Object function () { } has no method 'getTangentAt' TubeGeometry.js:175

I am getting this error while drawing Helix Curve. I've added latest Curve.js and TubeGeormetry.js. Is this because of Canvas rendering or Am I doing something wrong ? I am follwing this example http://mrdoob.github.com/three.js/examples/webgl_geometry_extrude_splines.html
<!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="Curve.js" type="text/javascript"></script>
<script src="TubeGeometry.js" type="text/javascript"></script>
<script src="Stats.js" type="text/javascript"></script>
<script src="Detector.js" type="text/javascript"></script>
<script>
// variables
var container, stats;
var camera, scene, renderer, splineCamera, cameraHelper, cameraEye;
var text, plane, tube, tubeMesh, parent;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var binormal = new THREE.Vector3();
var normal = new THREE.Vector3();
// extrudePath, Helix Curve
extrudePath = new THREE.Curve.create(
function() {
},
function(t) {
var a = 30; // radius
var b = 150; //height
var t2 = 2 * Math.PI * t * b / 30;
var tx = Math.cos(t2) * a,
ty = Math.sin(t2) * a,
tz = b * t;
return new THREE.Vector3(tx, ty, tz);
}
);
// Tube Geometry
var segments = 400;
var closed = false;
var debug = false;
var radiusSegments = 12;
// add tube
addTube();
function addTube()
{
alert('hello');
tube = new THREE.TubeGeometry(extrudePath, segments, 2, radiusSegments, closed, debug);
// Tube Mesh
tubeMesh = THREE.SceneUtils.createMultiMaterialObject( tube, [
new THREE.MeshLambertMaterial({
color: color,
opacity: geometry.debug ? 0.2 : 0.8,
transparent: true
}),
new THREE.MeshBasicMaterial({
color: 0x000000,
opacity: 0.5,
wireframe: true
})]);
parent.add(tubeMesh);
}
init();
animate();
function init(){
// container
container = document.createElement( 'div' );
document.body.appendChild( container );
// info div
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/> You can identify cylinder face by clicking on it.</br>';
container.appendChild( info );
// camera
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set(0,150,400);
// scene
scene = new THREE.Scene();
camera.lookAt(scene.position);
// light
scene.add( new THREE.AmbientLight( 0x404040 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 1, 0 );
scene.add( light );
// CONTROLS
controls = new THREE.TrackballControls( camera );
// 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 );
}
parent = new THREE.Object3D();
parent.position.y = 100;
scene.add( parent );
// 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( 'mouseover', onDocumentMouseOver, 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 onDocumentMouseOver( 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();
update();
}
function update()
{
controls.update();
stats.update();
}
function render() {
parent.rotation.y += ( targetRotation - parent.rotation.y ) * 0.05;
camera.updateMatrixWorld();
renderer.render( scene, camera );
}
</script>
</body>
</html>
you are not instantiating your curve object correctly. you should be doing
extrudePath = new (THREE.Curve.create(...))();
or in a way simpler to understand.
CustomCurve = THREE.Curve.create(...);
extrudePath = new CustomCurve();

three.js - can't create a Cylinder

I'm trying to create a Cylinder but with no success.
This is my code:
geometry02 = new THREE.CylinderGeometry( 20, 100, 100, 1000 );
material02 = new THREE.MeshBasicMaterial({color: 0x0000ff});
cylinder02 = new THREE.Mesh( geometry02, material02 );
cylinder02.position.x = 300;
scene.addObject( cylinder02 );
Am I forgetting to include something?
There is nothing wrong with the snippet you just posted. I can confirm it runs ok if I paste in an example.
Make sure that:
There aren't any javascript errors (check your browser's Console)
The camera is pointing in the right direction (as anshulkatta mentions, camera.lookAt(yourObject); is a good way to do that)
Your model's position/scale has decent values/is within the camera's frustrum/visible area
As a side note, you might want to decrease the segmentsRadius parameter(1000) to a smaller value. You might get a similar look/level detail with less vertices/faces.
Please try below code
<!DOCTYPE html>
<html lang="en">
<head>
<title>3d cylinder</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;
var cylinder, line, geometry;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
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';
container.appendChild( info );
// camera
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 20000 );
camera.position.y = 100;
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 map = THREE.ImageUtils.loadTexture( 'ash_uvgrid01.jpg' );
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;
materials = [
new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map, side: THREE.DoubleSide } ),
new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true, transparent: true, opacity: 0.1, side: THREE.DoubleSide } )
];
// 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
cylinder = THREE.SceneUtils.createMultiMaterialObject( new THREE.CylinderGeometry( 50, 50, 200, 25, 10, false ), materials );
cylinder.overdraw = true;
scene.add(cylinder);
// 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>

Categories

Resources