I am attempting to learn THREE and so far things are going well. I'm working to create a simple project building a golf ball on a golf tee. Eventually I'll put it inside a skybox and use some shaders to create the appearance of dimples in the ball.
For now I've been able to create the ball and the tee and get the camera and lights set up. I'm now attempting to add some orbit controls so I can rotate, pan and zoom around the scene. I added the orbitControls script and set it up how I see in the examples online. However when I attempt to orbit my camera snaps to the either 1,0,0 0,1,0 or 0,0,1 and eventually the scene completely fails and I end up looking along 0,0 with no object visible.
Here's my code in it's entirety
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>3D Sandbox</title>
<style>
html, body {
margin: 0px;
}
canvas {
background-color: #999;
position: absolute;
height: 100vh;
width: 100vw;
overflow: hidden;
}
</style>
</head>
<body>
<script src='/three.js'></script>
<script src="/orbitControls.js"></script>
<script type='text/javascript'>
let scene,
camera,
controls,
renderer,
height = window.innerHeight,
width = window.innerWidth;
window.addEventListener('load', init, false);
function init () {
createScene();
createCamera();
createLights();
createBall();
createTee();
render();
animate();
}
function createScene () {
let grid;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
grid = new THREE.GridHelper(100, 5);
scene.add(grid);
}
function createCamera () {
camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);
camera.position.z = 50;
camera.position.y = 13;
camera.up = new THREE.Vector3(0,1,0);
//camera.lookAt(new THREE.Vector3(0,13,0));
controls = new THREE.OrbitControls(camera);
controls.target = new THREE.Vector3(0, 13, 0);
controls.addEventListener('change', render);
}
function createLights () {
let directionalLight, ambientLight;
directionalLight = new THREE.DirectionalLight(0x404040, 4);
directionalLight.position.set(0, 2000, 2000);
directionalLight.target.position.set(0, 2, 0);
scene.add(directionalLight);
ambientLight = new THREE.AmbientLight(0x404040, 2);
scene.add(ambientLight);
}
function createBall () {
let ballGeom, ballMaterial, ball;
ballGeom = new THREE.SphereGeometry(5, 32, 32);
ballMaterial = new THREE.MeshPhongMaterial({
color: 0xFFFFFF
});
ball = new THREE.Mesh(ballGeom, ballMaterial);
ball.position.y = 13.3;
scene.add(ball);
}
function createTee () {
let tee, stemGeom, stem, bevelGeom, bevel, topGeom, top, teeMat;
tee = new THREE.Object3D();
teeMat = new THREE.MeshPhongMaterial({
color: 0x0000FF
});
stemGeom = new THREE.CylinderGeometry(.9, 0.75, 7);
stem = new THREE.Mesh(stemGeom, teeMat);
tee.add(stem);
bevelGeom = new THREE.CylinderGeometry(1.5, .9, 2);
bevel = new THREE.Mesh(bevelGeom, teeMat);
bevel.position.y = 3.75;
tee.add(bevel);
topGeom = new THREE.CylinderGeometry(1.5, 1.5, .25);
top = new THREE.Mesh(topGeom, teeMat);
top.position.y = 4.875;
tee.add(top);
tee.position.y = 3.5;
scene.add(tee);
}
function render () {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame( animate );
controls.update();
render();
}
</script>
</body>
</html>
In my case, the camera position was the same as OrbitControl target, and this made my OrbitControl seem "broken" (different symptoms than OP -- my OrbitControl just wouldn't work at all.)
As mentioned in this github comment, camera position and OrbitControl target cannot be the same; I repositioned my camera to fix this (camera.position.z = 10).
Remember, the camera (like any Object3D) is positioned at (0,0,0) by default, and the OrbitControl target property (a Vector3D) seems to also default that same point (0,0,0)
controls = new THREE.OrbitControls(camera);
needs to be
controls = new THREE.OrbitControls(camera, renderer.domElement);
The result is on this block.
Related
I want something like this:
https://drive.google.com/file/d/1v_4M59Ny93QwT52unfM9N_tfzo3xRAq1/view?usp=share_link
This is my code
<!DOCTYPE html>
<html>
<head>
<title>Three.js JPG Background with Custom Position</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r121/three.min.js"></script>
<script src="./js/tween.js/dist/tween.umd.js"></script>
<!-- Css -->
<style>
body {
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
}
</style>
</head>
<body>
<script>
// Initialize Three.js scene
var scene = new THREE.Scene();
var camera = new THREE.OrthographicCamera(window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 0.1,);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Load the Main BG texture
var mainBg = new THREE.TextureLoader().load("http://127.0.0.1:5500/img/main-bg.jpg");
// Create a full-screen plane to display the texture
var geometry1 = new THREE.PlaneGeometry(window.innerWidth, window.innerHeight);
var material1 = new THREE.MeshBasicMaterial({ map: mainBg });
var plane1 = new THREE.Mesh(geometry1, material1);
plane1.position.set(0, 0, 0)
scene.add(plane1);
// Create a full-screen plane to display the texture
var frame1 = new THREE.TextureLoader().load("http://127.0.0.1:5500/img/frame1.png");
var geometry2 = new THREE.PlaneGeometry(90, 110);
var material2 = new THREE.MeshBasicMaterial({ map: frame1 });
var plane2 = new THREE.Mesh(geometry2, material2);
plane2.position.set(-190, 130, .1);
scene.add(plane2);
// Check if mouse is over the child asset
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var zoomed = false;
// Mouse move function
function onMouseMove(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects([plane2]);
if (intersects.length > 0 && !zoomed) {
zoomed = true;
camera.position.set(plane2.position.x, plane2.position.y, plane2.position.z);
camera.lookAt(plane2.position.x, plane2.position.y, plane2.position.z);
} else if (intersects.length === 0 && zoomed) {
zoomed = false;
camera.position.set(0, 0, 5);
camera.lookAt(new THREE.Vector3(0, 0, 0));
}
}
// Mouse move function calling on moving mouse
document.addEventListener('mousemove', onMouseMove, false);
window.addEventListener('mousedown', function () {
gsap.to(camera.position, {
z: 15,
duration: 15
});
})
// Render loop
function render() {
camera.position.z = 5;
requestAnimationFrame(render);
renderer.render(scene, camera);
}
render();
</script>
</body>
</html>
assets:
frame1
and
main-bg
i made frame 1 on the center of the screen by hovering it but cannot make camera to zoom in on it. I tried tween but I think there is something wrong in the basics of my code
Sorry i am new to this and this is my first threejs project
You can apply a mousemove event on the canvas and use event.clientX or event.clientY to read live mouse pointer values. These values can then be used within the the listener to update values of camera.position.z to change zoom.
I am relatively new to ThreeJS.
I want to make a website very similar to this one:
Web de CraftedBYGC
In which I make a system of particles that as the user scrolls they disperse and rejoin in a form.
The truth is that I am very lost about where to start.
I would greatly appreciate some help.
I tried to create a geometry with particle mesh and move the camera on scroll to simulate a little bit the effect, but the truth was very poor. I need to find another method and I don't know well what to do...
Below is a snippet of the working example:
var webGLRenderer = initRenderer();
var scene = new THREE.Scene();
var camera = initCamera(new THREE.Vector3(-30, 40, 50));
// call the render function
var step = 0;
var knot;
// setup the control gui
var controls = new function () {
// we need the first child, since it's a multimaterial
this.radius = 13;
this.tube = 1.7;
this.radialSegments = 156;
this.tubularSegments = 12;
this.redraw = function () {
// remove the old plane
if (knot) scene.remove(knot);
// create a new one
var geom = new THREE.TorusKnotGeometry(controls.radius, controls.tube, Math.round(controls.radialSegments), Math.round(controls.tubularSegments), Math.round(controls.p), Math.round(controls.q));
knot = createPoints(geom);
// add it to the scene.
scene.add(knot);
};
};
var gui = new dat.GUI();
gui.add(controls, 'radius', 0, 40).onChange(controls.redraw);
gui.add(controls, 'tube', 0, 40).onChange(controls.redraw);
gui.add(controls, 'radialSegments', 0, 400).step(1).onChange(controls.redraw);
gui.add(controls, 'tubularSegments', 1, 20).step(1).onChange(controls.redraw);
controls.redraw();
render();
// from THREE.js examples
function generateSprite() {
var canvas = document.createElement('canvas');
canvas.width = 16;
canvas.height = 16;
var context = canvas.getContext('2d');
var gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2);
gradient.addColorStop(0, 'rgba(255,255,255,1)');
gradient.addColorStop(0.2, 'rgba(0,255,255,1)');
gradient.addColorStop(0.4, 'rgba(0,0,64,1)');
gradient.addColorStop(1, 'rgba(0,0,0,1)');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
return texture;
}
function createPoints(geom) {
var material = new THREE.PointsMaterial({
color: 0xffffff,
size: 3,
transparent: true,
blending: THREE.AdditiveBlending,
map: generateSprite(),
depthWrite: false // instead of sortParticles
});
var cloud = new THREE.Points(geom, material);
return cloud;
}
function render() {
knot.rotation.y = step += 0.01;
// render using requestAnimationFrame
requestAnimationFrame(render);
webGLRenderer.render(scene, camera);
}
body {
margin: 0;
overflow: none
}
<!DOCTYPE html>
<html>
<head>
<title>Example 07.11 - 3D Torusknot</title>
<script type="text/javascript" charset="UTF-8" src="https://www.smartjava.org/ltjs3/libs/three/three.js"></script>
<script src="https://www.smartjava.org/ltjs3/libs/three/controls/TrackballControls.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.9/dat.gui.min.js"></script>
<script src="https://www.smartjava.org/ltjs3/src/js/util.js"></script>
</head>
<body>
<div id="webgl-output">
</body>
</html>
This is working on a TorusKnot, but you can apply the particles to a model, too. All you have to do is change the source.
In this question, I asked about how one would moves a camera to a different position relative to a target. A very kind gentleman #TheJim01 provided a veery nice answer.
However, I am getting issues with this where the camera is rotated and positioned strangely after I move it.
What are the strategies to keep the camera rotated and maintaining its view of the target smoothly?
You can use any tweening library (Tween.js, GSAP) to move your camera smoothly from current position to the position atop of the sphere.
Also, use THREE.Spherical() to compute the final point. And don't forget to use .makeSafe() method.
body {
overflow: hidden;
margin: 0;
}
button{
position: absolute;
font-weight: bold;
}
<button id="moveUp">MOVE UP</button>
<script src="https://cdn.jsdelivr.net/npm/gsap#3.5.1/dist/gsap.min.js"></script>
<script type="module">
import * as THREE from "https://cdn.jsdelivr.net/npm/three#0.121.1/build/three.module.js";
import { OrbitControls } from "https://cdn.jsdelivr.net/npm/three#0.121.1/examples/jsm/controls/OrbitControls.js";
let scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x000000, 6, 15);
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 100);
camera.position.set(0, 0, 10);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
let controls = new OrbitControls(camera, renderer.domElement);
controls.maxDistance = 10;
controls.minDistance = 7;
let sphere = new THREE.Mesh(new THREE.SphereBufferGeometry(4, 36, 18), new THREE.MeshBasicMaterial({color: "aqua", wireframe: true}));
scene.add(sphere);
moveUp.addEventListener("click", onButtonClick);
let spherical = new THREE.Spherical();
let startPos = new THREE.Vector3();
let endPos = new THREE.Vector3();
let axis = new THREE.Vector3();
let tri = new THREE.Triangle();
function onButtonClick(event){
spherical.setFromVector3(camera.position);
spherical.phi = 0;
spherical.makeSafe(); // important thing, see the docs for what it does
endPos.setFromSpherical(spherical);
startPos.copy(camera.position);
tri.set(endPos, scene.position, startPos);
tri.getNormal(axis);
let angle = startPos.angleTo(endPos);
let value = {value: 0};
gsap.to(value, {value: 1,
duration: 2,
onUpdate: function(){
camera.position.copy(startPos).applyAxisAngle(axis, angle * value.value);
controls.update();
},
onStart: function(){
moveUp.disabled = true;
},
onComplete: function(){
moveUp.disabled = false;
}
})
.play();/**/
}
renderer.setAnimationLoop(()=>{
renderer.render(scene, camera);
});
</script>
The better way to smoothly translate a camera would be to create keyframes and position them in some form of timeline defined by a emphasys curve.
Hi i have created x and y co-ordinates. How to labeling the co-ordinates axes like i am showing the below image. how to move the labels when we resize the co-ordinate lines using animate in three.js
but am not able move the labels when i resize the co-ordinate lines
below is my expected image and the code which i used
1
-
-
-
-
x ---------------------------- y
-
-
-
-
2
code
<style type="text/css">
body {
/* Set the background color of the HTML page to black */
background-color: #000000;
/* Hide oversized content. This prevents the scroll bars. */
overflow: hidden;
}
</style>
<!-- Include Three.js libraries -->
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/Detector.js"></script>
<script src="https://threejs.org/examples/js/renderers/CanvasRenderer.js"></script>
<script src="https://threejs.org/examples/js/renderers/Projector.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<!-- This is the DIV element which will contain the WebGL canvas. To be identifiable later on,
the id 'WebGLCanvas' is applied to it. -->
<div id="overlaytext1" style="position:relative; top: 290px; left: 1030px;color:white;">a</div>
<div id="overlaytext2" style="position:relative; top: 800px; left: 1030px;color:white;">b</div>
<div id="WebGLCanvas">
<!-- This JavaScript block encloses the Three.js commands -->
<script>
var scene;
var camera;
var renderer;
initializeScene();
renderScene();
animate();
function initializeScene() {
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500);
camera.position.set(0, 0, 100);
camera.lookAt(new THREE.Vector3(0, 0, 0));
var material = new THREE.LineBasicMaterial({
color: 0x0000ff
});
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(0, -20, 0));
geometry.vertices.push(new THREE.Vector3(0, 30, 0));
var line = new THREE.Line(geometry, material);
var geometry2 = new THREE.Geometry();
geometry2.vertices.push(new THREE.Vector3(-10, 0, 0));
geometry2.vertices.push(new THREE.Vector3(10, 0, 0));
var geometry3 = new THREE.Geometry();
geometry3.vertices.push(new THREE.Vector3(-10, 0, 0));
geometry3.vertices.push(new THREE.Vector3(0, 200, 0));
var line1 = new THREE.Line(geometry, material);
var line2 = new THREE.Line(geometry2, material);
var line3 = new THREE.Line(geometry3, material);
scene.add(line1);
scene.add(line2);
/*scene.add(line3); */
controls = new THREE.OrbitControls(camera, renderer.domElement);
}
function renderScene() {
renderer.render(scene, camera);
}
function animate() {
// Read more about requestAnimationFrame at http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimationFrame(animate);
// Render the scene.
renderer.render(scene, camera);
controls.update();
}
</script>
</div>
I load some objects using the ctm binary loader in Threejs r69. This returns Mesh objects using a BufferGeometry internally.
I need to remove from the scene then delete one of these Meshes, including their material/texture/geometry. According to examples and google, I should use:
scene.remove(m_mesh);
m_mesh.geometry.dispose();
m_mesh.geometry = null;
m_mesh.material.dispose();
m_mesh.material = null;
m_mesh = null;
This removes the object from the scene, but the screen goes black for a second, and I've got a GL error :
Error: WebGL: drawElements: no VBO bound to enabled vertex attrib index 2!
Looks like the above sequence (ran in my render() operation, just before drawing the scene) did not clean everything, or at least I still have references to non existing VBOs somewhere.
I've spent quite some time debugging the problem and came to the conclusion that this happens only when using an orthographic camera with a Sprite and a Perspective camera, in 2 differents scenes.
Basically, I draw a flat background using a Sprite and a dedicated scene, then my 3D scene with Meshes. If I delete a mesh from the 3D scene, then the drawing of the flat background fails.
I can't figure out why. Looks like there's a side effect of deleting a Mesh on Sprites, even if attached to different scenes.
If I comment the background drawing, then the deletion of my mesh works perfectly.
I insert below a reproduction of the problem using the standard threejs distribution. Wait about 5 seconds and you should see some GL errors on the jaavscript console.
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - geometries</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;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="build/three.min.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, scene, renderer;
frame_count = 0;
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;
// I need a second camera for my 2D sprite (used as a background)
// must use another texture so that it's not destroyed when removing the first object
cameraOrtho = new THREE.OrthographicCamera(window.innerWidth / -2,
window.innerWidth / 2,
window.innerHeight / 2,
window.innerHeight / -2,
1, 10);
cameraOrtho.position.z = 10;
cameraOrtho.position.y = 400;
sceneBackground = new THREE.Scene();
var map1 = THREE.ImageUtils.loadTexture('textures/disturb.jpg');
var material1 = new THREE.SpriteMaterial({
map: map1
});
var spriteBackground = new THREE.Sprite(material1);
spriteBackground.scale.set(window.innerWidth, window.innerHeight, 1);
spriteBackground.position.set(window.innerWidth / 2,
window.innerHeight / 2);
sceneBackground.add(spriteBackground);
scene = new THREE.Scene();
var light;
my_object = null;
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/UV_Grid_Sm.jpg');
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;
var material = new THREE.MeshLambertMaterial({
map: map,
side: THREE.DoubleSide
});
// one object is enough to demonstrate
// can't reproduce the problem with a standard SphereGeometry
// try to convert it to a BufferGeometry
var sphereGeometry = new THREE.SphereGeometry(75, 20, 10);
var bufferGeometry = new THREE.BufferGeometry().fromGeometry(sphereGeometry);
my_object = new THREE.Mesh(bufferGeometry, material);
my_object.position.set(-400, 0, 200);
scene.add(my_object);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.autoClear = false;
renderer.autoClearDepth = false;
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 animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
frame_count++;
var timer = Date.now() * 0.0001;
camera.position.x = Math.cos(timer) * 800;
camera.position.z = Math.sin(timer) * 800;
camera.lookAt(scene.position);
//after a few frames I want to destroy completely the object
//means remove from the scene, remove texture, material, geometry
//note that here it's a Geometry, not a BufferGeometry
//may be different
if (frame_count > 60 * 5) {
if (my_object != null) {
console.log("destroy object buffer");
scene.remove(my_object);
my_object.material.map.dispose();
my_object.material.dispose();
my_object.geometry.dispose();
my_object = null;
}
}
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(sceneBackground, cameraOrtho);
renderer.clearDepth();
renderer.render(scene, camera);
}
</script>
</body>
</html>
Any hints on how to fix this issue?
Thank you,
Pascal