How do I load an image in three.js? - javascript

I'm trying to map a picture of the earth at night to a sphere with three.js, but I can't get it working. Everytime I refresh the page the image hasn't mapped to the sphere and in the console I get error 404 (Not Found). I've tried a lot of different ways to reference my image, but none of them worked.
This is my javascript code:
import './style.css'
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight);
camera.position.z = 3;
scene.add(camera);
const textureLoader = new THREE.TextureLoader();
const nightMapEarth = textureLoader.load("assets/nightmapearth.jpg");
const sphereGeometry = new THREE.SphereGeometry(0.7);
const material = new THREE.MeshBasicMaterial({
map: nightMapEarth,
});
const earth = new THREE.Mesh(sphereGeometry, material);
scene.add(earth);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.append(renderer.domElement);
function animate() {
window.requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();

Related

Three.js texture does not load

I'm trying to make a model of planet Earth, but the texture doesn't load and I don't know why this happens, I tried to change the image format and also use it as an export link and it still doesn't work.
my code:
import * as THREE from 'https://cdn.skypack.dev/three#0.134.0'
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer(
);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(5, 50, 50),
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load('.img/global.jpeg')
})
);
scene.add(sphere);
camera.position.z = 15;
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
My first suggestion is for you to split up your code into individual steps so you can pinpoint where the error is taking place. Additionally, TextureLoader.load() has a few callback functions that you can help you determine if loading was successful or if it failed:
const geom = new THREE.SphereGeometry(5, 50, 50);
const texLoader = new THREE.TextureLoader();
const texture = texLoader.load(
// Location
'.img/global.jpeg',
// On success
function(texture) {
console.log("Success!");
console.log(texture);
},
// Progress (ignored)
undefined,
// On error
function(err) {
console.log("Error");
console.log(err);
}
);
const mat = new THREE.MeshBasicMaterial({map: texture});
const sphere = new THREE.Mesh(geom, mat);
Then you can check your console to see what the logs are displaying.

Setting the position of a text geometry?

I have looked through stack overflow and google and I have found how to CENTER a text geometry but that is not what I want to do.
I have a scene that just has a block of text that says "Buy Here!". Using the documentation in the three.js website and examples here I was able to do that after some struggling. I had some trouble finding out how to refer to that mesh since I had created the geometry inside a function, and it took hours for me to know about setting a name for it as a string so it can be accessible from different parent/child levels.
What I am NOT able to do now is to offset the text by some arbitrary number of units. I tried shifting it down by 5 units. No matter how I try to do it it isn't working. I either manage to make the text geometry disappear OR my whole scene is black.
Here is my code...
I have the basic scene setup working properly and I'll include it here but feel free to skip since I'm pretty sure this has nothing to do with the issue...
import './style.css'
import * as THREE from 'three';
import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/three#0.117.0/examples/jsm/controls/OrbitControls.js';
import TWEEN from 'https://cdn.jsdelivr.net/npm/#tweenjs/tween.js#18.5.0/dist/tween.esm.js';
//BASIC SCENE SETUP
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
//LIGHTS (POINT AND AMBIENT)
const pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.set(5, 5, 5);
const ambientLight = new THREE.AmbientLight(0xFFFFFF);
scene.add(pointLight, ambientLight);
//RESIZE WINDOW
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
render();
}, false);
//ORBIT CONTROLS
const controls = new OrbitControls(camera, renderer.domElement);
controls.minDistance = 5;
controls.maxDistance = 70;
controls.enablePan = false;
controls.enableRotate = false;
controls.enableZoom = false;
controls.target.set(0,0,-1);
camera.position.setZ(25);
window.addEventListener("click", (event) => {
onClick(event);
})
window.addEventListener("mousemove", onMouseMove);
var animate = function() {
requestAnimationFrame(animate);
controls.update();
render();
TWEEN.update();
};
function render() {
renderer.render(scene, camera);
}
animate();
and here is my code for the text object....
var loaderF = new THREE.FontLoader();
loaderF.load( 'https://threejs.org/examples/fonts/optimer_regular.typeface.json', function ( font ) {
var geometry = new THREE.TextGeometry( 'Buy Here!', {
font: font,
size: 2.3,
height: 0.1,
curveSegments: 15,
bevelEnabled: true,
bevelThickness: 0.5,
bevelSize: 0.31,
bevelSegments: 7
} );
geometry.center();
var material = new THREE.MeshLambertMaterial({color: 0x686868});
var mesh = new THREE.Mesh( geometry, material );
mesh.name = "bhText"
scene.add( mesh );
mesh.userData = { URL: "http://google.com"};
} );
Here's what I have tried.....
under "var geometry ({...});" I typed....
geometry.position.setX(-5);
but the text object disappears completely so I tried
geometry.position.setX = -5;
but there was no difference so i tried taking out
geometry.center();
but it had the same results.
So then I tried using
mesh.position.x = -5;
with AND without
geometry.center();
but again, they all just make my text object disappear.
So now I tried to set the position from outside the function by typing the following code OUTSIDE of everything that is contained in
loaderF.load ('https.....', function (font){var geometry = .....})
using the reference I learned....
scene.getObjectByName("bhText").position.x(-5);
but this makes my entire scene go blank (black). So I tried variations of like
scene.getObjectByName("bhText").position.x = -5;
scene.getObjectByName("bhText").position.setX(-5);
scene.getObjectByName("bhText").position.setX = -5;
mesh.position.setX = -5;// I was pretty sure this wasn't going to work since I wasn't
//using the mesh name specifically for when it's inside something
//I can't reach because of parent-child relations
and again trying each of those with AND without
geometry.center();
but they all made my scene go black.
I just wanna move it down a couple of units. Sheesh.
Could anyone be kind enough to tell me WHERE in my code I can set the position of the text geometry? Thank you please.
I just wanna move it down a couple of units.
In this case use mesh.position.y = - 5;. Changing the x coordinate will move the mesh to the left or right. Here is a complete live example based on your code:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set( 0, 0, 10 );
const renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
const pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.set(5, 5, 5);
const ambientLight = new THREE.AmbientLight(0xFFFFFF);
scene.add(pointLight, ambientLight);
const loader = new THREE.FontLoader();
loader.load('https://threejs.org/examples/fonts/optimer_regular.typeface.json', function(font) {
const geometry = new THREE.TextGeometry('Buy Here!', {
font: font,
size: 2,
height: 0.5
});
geometry.center();
const material = new THREE.MeshLambertMaterial({
color: 0x686868
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.y = - 1; // FIX
mesh.name = "bhText"
scene.add(mesh);
renderer.render(scene, camera);
});
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.130.1/build/three.min.js"></script>

Three.js - Why is csg.js not working for boolean operations?

I'm new to both three.js and csg.js. I've created a basic scene like this:
// Create scene
const scene = new THREE.Scene();
// Create perspective camera - FOV, aspect ratio, near + far clipping plane
const camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 10000);
// Create renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
And I'm trying to subtract a circle from a plane.
// Create plane geometry
const pgeometry = new THREE.PlaneGeometry();
const pmaterial = new THREE.MeshBasicMaterial({color: 0xE8ADAA, opacity: 0.7, transparent: true});
const plane = new THREE.Mesh(pgeometry, pmaterial);
plane.position.z = 3;
// Create circle BoxGeometry
const ogeometry = new THREE.CircleGeometry(0.5, 32);
const omaterial = new THREE.MeshBasicMaterial({color: 0xE8ADAA});
const circle = new THREE.Mesh(ogeometry, omaterial);
circle.position.z = 3;
// CSG test
const bspPlane = new ThreeBSP(plane);
const bspCircle = new ThreeBSP(circle);
const bspResult = bspPlane.subtract(bspCircle);
const result = bspResult.toMesh();
scene.add(result);
(Then I have this at the end, to render the scene from the camera.)
// Camera position on z-axis
camera.position.z = 5;
// Render scene from camera
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
The three.js portion (rendering the plane and the circle by using `scene.add()' works, and I've attached three-js-csg, csg, and three-2-csg in the HTML in hopes of getting something to work. Is there anything glaringly wrong?
Thanks.
CSG doesn’t work with two non-manifold geometries. Your plane and circle are infinitely thin so the math of subtracting one from the other doesn’t work.
You need to use geometry that has an “inside” and “outside”, so instead of a plane, use a cube with a small depth. Instead of a circle, use a cylinder.

Cant get Scene to render in Three.js

I'm pretty new to three.js and I can't seem to get my scene (or camera) to render. The other parts are working (I am able to render my adobe illustrator vectors that I converted just fine), however if I comment out my scene, camera & renderer code it makes no difference to what's rendered in the browser.
Here is my html:
<canvas id ="slot">
</canvas>
Here is my js:
var c = document.getElementById('slot');
c.height = 282;
c.width = 400;
var cx = c.getContext('2d');
//This doesn't appear to be working ...
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 );
//Working just fine
cx.fillStyle="rgba(255,255,255,0)";
cx.fillRect(0,0,1,1);
cx.fillRect(1,0,1,1);
//....(goes on and on)
var slot = new THREE.Mesh(cx);
// GridHelper
var size = 10;
var divisions = 10;
var gridHelper = new THREE.GridHelper( size, divisions )
// Light
var light = new THREE.AmbientLight(0x404040);
// Fog
var fogColor = 0xFFFFFF;
var near = 10;
var far = 100;
var fog = new THREE.Fog(fogColor, near, far)
scene.add(slot, gridHelper, light, fog)
camera.position.z = 5;
renderer.render( scene, camera );
any help would be greatly appreciated
I have prepared a jsFiddle with your corrected code.
https://jsfiddle.net/EthanHermsey/qampc5b1/49/
var renderer = new THREE.WebGLRenderer({antialias: true});
var cTexture = new THREE.CanvasTexture( c );
var slot = new THREE.Mesh(
new THREE.PlaneGeometry(2, 2),
new THREE.MeshBasicMaterial({
map: cTexture,
transparent: true
})
);
scene.add(slot);
scene.fog = new THREE.Fog(fogColor, near, far);
You cant initialize a Mesh like that.
You have to add the canvas as a CanvasTexture to a material.
You cant .add() fog to the scene, it is like this: scene.fog = new THREE.Fog().
This is what gave the error message.
I don't think you can add multiply objects to the scene like that. (but i'm not sure)
Added antialias to the render (makes edges smoother).

Three js in a class

I tried to set all the necessary functionality into one class in order to create a simple three.js scene with a cube. I don't get any errors, but the scene stays black when I open it in the browser.
Here is my code:
class SceneInit {
constructor(fov = 45,camera,scene,controls,renderer)
{
this.camera = camera;
this.scene = scene;
this.controls = controls;
this.renderer = renderer;
this.fov = fov;
}
initScene() {
this.camera = new THREE.PerspectiveCamera(this.fov, window.innerWidth / window.innerHeight, 1, 1000);
this.camera.position.z = 15;
this.controls = new THREE.TrackballControls( this.camera );
//this.controls.addEventListener('change', this.renderScene);
this.scene = new THREE.Scene();
//specify a canvas which is already created in the HTML file and tagged by an id //aliasing enabled
this.renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myThreeJsCanvas') , antialias: true});
this.renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(this.renderer.domElement);
//ambient light which is for the whole scene
let ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
ambientLight.castShadow = false;
this.scene.add(ambientLight);
//spot light which is illuminating the chart directly
let spotLight = new THREE.SpotLight(0xffffff, 0.55);
spotLight.castShadow = true;
spotLight.position.set(0,40,10);
this.scene.add(spotLight);
//if window resizes
window.addEventListener('resize', this.onWindowResize, false);
}
animate(){
requestAnimationFrame( this.animate.bind(this) );
this.render();
this.controls.update();
}
render(){
this.renderer.render( this.scene, this.camera );
}
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize( window.innerWidth, window.innerHeight );
}
}
And then I try to instantiate a new object and add an object to the scene. When I try to print the children of the scene, it returns me the right objects, but as I mentioned before the scene stays black. Only the renderer window is getting drawed in the browser.
let test = new SceneInit(45);
test.initScene();
test.animate();
let geometry = new THREE.BoxBufferGeometry( 200, 200, 200 );
let material = new THREE.MeshBasicMaterial();
let mesh = new THREE.Mesh( geometry, material );
test.scene.add(mesh);
console.log(test.scene.children); //returns 3 objects (ambientLight, spotLight, mesh)
I got the answer.
The problem in the code was that the BoxGeometry was too big and the camera was inside the box. With the clipping set to 1 it wouldn't even render it.
So the solution is to set a smaller BoxGeometry. or to move the camera away!

Categories

Resources