Unable to use DragControls - javascript

I am a beginner with three.js and I was trying to implement a feature where one must be able to drag a 3d model. I came across DragControl in this process and I am not able to use it in my code.
when I use new DragControls(objects, camera, renderer.domElement) I get this error
capture.js:9 Uncaught ReferenceError: DragControls is not defined
at capture.js:9
and when i use the new THREE.DragControls(objects, camera, renderer.domElement) I get This error
Uncaught TypeError: THREE.DragControls is not a constructor
How can I solve this issue?
My complete code is as follows:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xff0000, .5 );
DragControls.install({THREE: THREE});
var controls = new DragControls( object, camera, renderer.domElement );
document.body.appendChild( renderer.domElement );
var light1 = new THREE.AmbientLight( 0xffffff );
light1.position.set(0, -70, 100).normalize();
scene.add(light1);
var light2 = new THREE.AmbientLight( 0xffffff );
light2.position.set(0, 70, 100).normalize();
scene.add(light2);
var geometry = new THREE.BoxGeometry();
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 25;
var object
controls.addEventListener( 'dragstart', function ( event ) {
event.object.material.emissive.set( 0xaaaaaa );
} );
controls.addEventListener( 'dragend', function ( event ) {
event.object.material.emissive.set( 0x000000 );
} );
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Locate the user</title>
<meta name="viewport" content="width=device-width,
user-scalable=no, initial-scale=1, maximum-scale=1, user-scalable=0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="js/three.min.js"></script>
<script src="js/GLTFLoader.js"></script>
<script src="js/drag-controls.js"></script>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="js/capture.js"></script>
</body>
</html>

Here is an updated version of your code. There were some conceptual issues in your code.
It seems you were mixing module vs non-module imports. The live example uses traditional global scripts (and not ES6 imports).
You did not render your scene once. The code has now an animation loop.
You added instances of AmbientLight and configured a position which is not necessary.
The lights have no effect anyway since you use MeshBasicMaterial which is an unlit material (meaning it does not react on lights).
You have created DragControls which object has first parameter which is an undefined variable in your code. Besides, the ctor only accepts an array and not single objects.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 5;
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xff0000, .5 );
var geometry = new THREE.BoxGeometry();
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
var controls = new THREE.DragControls( [ cube ], camera, renderer.domElement );
document.body.appendChild( renderer.domElement );
controls.addEventListener( 'dragstart', function ( event ) {
event.object.material.color.set( 0xaaaaaa );
} );
controls.addEventListener( 'dragend', function ( event ) {
event.object.material.color.set( 0x000000 );
} );
animate();
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
<script src="https://cdn.jsdelivr.net/npm/three#0.115/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.115/examples/js/controls/DragControls.js"></script>

Related

How to create sea waves in three.js?

I was making ocean waves in three.js but when I run it on web browser, it just displays white screen.
The code I used to create the ocean waves is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/three#0.143/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.143/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.143/examples/js/objects/Water.js"></script>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.set( 0, 0, 50 );
camera.lookAt( 0, 0, 0 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const WaterGeometry = new THREE.PlaneGeometry( 45, 45 );
const texture = new THREE.TextureLoader().load( 'https://i.imgur.com/mK9cHLq.jpeg' );
const material = new THREE.MeshBasicMaterial( { map: texture, side: THREE.DoubleSide } );
const controls = new THREE.OrbitControls( camera, renderer.domElement );
const params = {
color: '#ffffff',
scale: 4,
flowX: 1,
flowY: 1
};
water = new THREE.Water( WaterGeometry, material, {
color: params.color,
scale: params.scale,
flowDirection: new THREE.Vector2( params.flowX, params.flowY ),
textureWidth: 1024,
textureHeight: 1024
} );
controls.update();
scene.add( water );
function animate()
{
requestAnimationFrame( animate );
water.rotation.x += 0.00;
water.rotation.y += 0.00;
water.rotation.z += 0.01;
renderer.render( scene, camera );
};
animate();
</script>
</body>
</html>
Where did I messed up? All I now see is the slowly rotating black square now.
I thank you for all the feedbacks. How to fix this error?
Thank you!
Your imports are messed up. Try it like so:
<script src="https://cdn.jsdelivr.net/npm/three#0.143/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.143/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.143/examples/js/objects/Water.js"></script>
Keep in mind to never import three.js files from different sources and releases.

three.js r81: How can do i make a cube with diffrent textures on each face

I just updated to the latest version of three.js,
and THREE.ImageUtils.loadTexture doesn't work anymore.
So i searched for cubes with different faces but they all
use the old technique " new THREE.ImageUtils.loadTexture".
I tried making one with "new THREE.TextureLoader.load(' texture1.png ')".
This is what i have:
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - geometry - cube</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 {
margin: 0px;
background-color: #000000;
overflow: hidden;
}
</style>
</head>
<body>
<script src="library/threejs/build/three.js"></script>
<script>
var camera, scene, renderer;
var head;
var loader = new THREE.TextureLoader();
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 400;
scene = new THREE.Scene();
materials = [
new THREE.TextureLoader().load( 'textures/mob/zombie/zombie_headfront.png' ),
new THREE.TextureLoader().load( 'textures/mob/zombie/zombie_headback.png' ),
new THREE.TextureLoader().load( 'textures/mob/zombie/zombie_headleft.png' ),
new THREE.TextureLoader().load( 'textures/mob/zombie/zombie_headright.png' ),
new THREE.TextureLoader().load( 'textures/mob/zombie/zombie_headup.png' ),
new THREE.TextureLoader().load( 'textures/mob/zombie/zombie_headdown.png' )];
head = new THREE.Mesh(
new THREE.BoxBufferGeometry(80, 80, 80, 1, 1, 1, materials),
new THREE.MeshBasicMaterial({ map: materials })
);
scene.add( head );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
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 );
head.rotation.x += 0.005;
head.rotation.y += 0.01;
renderer.render( scene, camera );
}
</script>
</body>
</html>
but i'm getting the error:
TypeError: offset is undefined
and
THREE.WebGLShader: Shader couldn't compile
and also
THREE.WebGLShader: gl.getShaderInfoLog() fragment ERROR: 0:238:
'mapTexelToLinear' : no matching overloaded function found
So if you know how to fix this or just know how to make a cube with 6 different sides that would be awesome!
thanks!
THREE.js has an undocumented material, THREE.MeshFaceMaterial which has been deprecated for a while now but still works in r81.
// Make an array of six regular materials
var materials = [
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/8B1rYNY.png")}),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/8w6LAV6.png")}),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/aVCY4ne.png")}),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/tYOW02D.png")}),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/nVAIICM.png")}),
new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://i.imgur.com/EDr3ed3.png")})
];
var geometry = new THREE.BoxBufferGeometry(200, 200, 200);
// Use THREE.MeshFaceMaterial for the cube, using the array as the parameter
mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
Demo
Apparently the way this works internally is by creating a THREE.BufferGeometry plane for each face of the cube and applying each material to a face (mrdoob himself). In other words, if this method stops working your alternative is to manually make a cube out of 6 planes, make them children of a null object so you can treat them as a single cube, and then apply your materials to each plane separately.
If you don't need to dynamically determine the cube faces at runtime and can "bake" them into a texture, a technically better (but more difficult) option is to use UV mapping.

Textures are Black in Three.JS

I have a model i'm exporting from blender 2.76b into json and then loading with three.js 71. Blender the model looks fine. In webGL the model is completely black. I'm think it has something to do with the textures but i'm not sure. The model is a fairly complex model made from maya and exported as an fbx. I've tested with simpler models and different textures and not had any problems but there's something wrong with this one.
Any suggestions would be appreciated greatly.
Link to the json: http://we.tl/GnQiOfAhOD
Here's the code.
<!DOCTYPE html>
<html lang="en">
<head>
<title>MultiLoader</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: #000;
color: #000;
margin: 0px;
overflow: hidden;
}
#info {
text-align: center;
padding: 10px;
z-index: 10;
width: 100%;
position: absolute;
}
a {
text-decoration: underline;
cursor: pointer;
}
#stats { position: absolute; top:0; left: 0 }
#stats #fps { background: transparent !important }
#stats #fps #fpsText { color: #aaa !important }
#stats #fps #fpsGraph { display: none }
</style>
</head>
<body>
<div id="info">MultiLoader Testing</div>
<script src="build/three.js"></script>
<script src="js/OrbitControls.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
<script src="js/ColladaLoader.js"></script>
<script src="js/OBJLoader.js"></script>
<script>
WIDTH = window.innerWidth,
HEIGHT = window.innerHeight;
VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 1,
FAR = 10000;
var container, stats;
var camera, scene, renderer;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
// SCENE
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xffffff, 500, 10000 );
// CAMERA
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
camera.position.set(60, 40, 120);
camera.lookAt(scene.position);
scene.add(camera);
//LIGHTS
var front = new THREE.DirectionalLight( 0xffffff, 5.4 );
front.position.set( 0, 140, 1500 );
front.position.multiplyScalar( 1.1 );
//front.color.setHSL( 0.6, 0.075, 1 );
scene.add( front );
var ambient = new THREE.AmbientLight(0xffffff);
scene.add( ambient );
var back = new THREE.DirectionalLight( 0xffffff, 0.5 );
back.position.set( 0, -140, -1500);
scene.add( back );
//Avatar Tests
var loader = new THREE.JSONLoader();
loader.load('models/Maya/modelExport.json', function ( geometry, materials ) {
material = new THREE.MeshFaceMaterial( materials );
avatar = new THREE.Mesh( geometry, material );
}
);
loader.onLoadComplete=function(){
avatar.scale.set(30, 30, 30);
var position = new THREE.Vector3(0,-20,0);
avatar.position.add(position);
scene.add( avatar );
}
// RENDERER
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( scene.fog.color );
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMapEnabled = true;
container.appendChild( renderer.domElement );
// Orbit Controls
controls = new THREE.OrbitControls( camera, renderer.domElement );
//controls.addEventListener( 'change', render ); // add this only if there is no animation loop (requestAnimationFrame)
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = true;
//
stats = new Stats();
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 animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
</body>
</html>
There are several issues with the code and model.
For the model: The entry mapLight should have been named mapDiffuse. I know you are exporting the model so you need to find how to make this happen.
For the code:
Your ambient light is very strong. It washes out everything. Try a value of 0x222222 or remove it from the scene totally.
Your camera does not need to be added to the scene.
Remove renderer.setClearColor( fog_color ) just to see if you get the correct meshes and materials first. Then you can go the scene effects.
Your texture size is way big. It is not supported in webgl. Try a size of 1024 and then move up is you need to.
Finally your loader.onLoadComplete() is never called (and will never be). Move that part of the code in your loader.load() callback function.
After all this you will see your girl.

TextGeometry not displaying, Could anyone tell me why?

I have the following Three.js code:
<html>
<head>
<title>My first Three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script src="js/three.min.js"></script>
<script src="js/optimer_regular.typeface.js"></script>
<script>
//Basic Three components
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//Let´s add a cube
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
//Let´s add a text
var material2 = new THREE.MeshPhongMaterial({
color: 0x00ff00
});
var textGeom = new THREE.TextGeometry( 'Sitescope', {
font: 'optimer',
weight: 'normal'
});
var textMesh = new THREE.Mesh( textGeom, material2 );
scene.add( textMesh );
//Render scene
function render() {
requestAnimationFrame( render );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
}
render();
</script>
</body>
When i run my code, My cube renders well but my text does not appear anywhere.
The only output that i get in the javascript console is:
THREE.WebGLRenderer 69.
Could anyone tell me why my text does not appear? (I am a beginner in Three.js) Thanks!
When using a THREE.MeshPhongMaterial() you need a light in the scene. Otherwise the model will come out black. If your scene background is also black you will never know if the model was drawn or not. Take a look at this fiddle. I am using THREE.MeshNormalMaterial(). Replace it with PhongMaterial to see what I am talking about. You can see the text is being drawn with black color just because it is over the green cube.

How to change the background by buttons on three.js?

I am new in three.js and using the following code I want to know how to change the background by clicking a button. So I think there is something different than using "switch" and "break". Here is something with .loadTexture am I right?
<html lang="en">
<head>
<title>gyroscopic</title>
<meta charset="utf-8">
<meta name="viewport" content="user-scalable=no, initial-scale=1">
<style>
body {
margin: 0px;
background-color: #000000;
overflow: hidden;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="three.min.js"></script>
<script src="DeviceOrientationControls.js"></script>
<script>
(function() {
"use strict"
window.addEventListener('load', function() {
var container, camera, scene, renderer, controls, geometry, mesh;
var animate = function(){
window.requestAnimationFrame( animate );
controls.update();
renderer.render(scene, camera);
};
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 1100);
controls = new THREE.DeviceOrientationControls( camera );
scene = new THREE.Scene();
var geometry = new THREE.SphereGeometry( 500, 316, 18 );
geometry.applyMatrix( new THREE.Matrix4().makeScale( -1, 1, 1 ) );
var material = new THREE.MeshBasicMaterial( {
map: THREE.ImageUtils.loadTexture( 'pic.jpg' )
} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
var geometry = new THREE.BoxGeometry( 100, 100, 100, 4, 4, 4 );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.style.position = 'absolute';
renderer.domElement.style.top = 0;
container.appendChild(renderer.domElement);
window.addEventListener('resize', function() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}, false);
animate();
}, false);
})();
</script>
</body>
</html>
You should be able to change the texture using .loadTexture on a button click listener.
So you would probably add something like this to your HTML:
<button id="change-background">Change Background</button>
Then in Javascript:
var backgroundButton = document.getElementById('change-background');
backgroundButton.addEventListener('click', function(){
material.map = THREE.ImageUtils.loadTexture('//new image path//');
});
You'll obviously need to replace the //new image path// with whatever URL you have for the new image.
The only question would be whether this updates the material on the mesh as well. I'm sure it does, but have no way of testing it at present.

Categories

Resources